"use server";

import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import prisma from "@/lib/prisma";
import bcrypt from "bcryptjs";

export type ActionState = { error: string } | null;

export async function login(prevState: ActionState, formData: FormData): Promise<ActionState> {
  const username = formData.get("username") as string;
  const password = formData.get("password") as string;

  if (!username || !password) {
    return { error: "Kullanıcı adı ve şifre gereklidir" };
  }

  // Fallback to initial .env credentials if no users exist
  const userCount = await prisma.user.count();
  if (userCount === 0) {
    if (
      username === process.env.ADMIN_USERNAME &&
      password === process.env.ADMIN_PASSWORD
    ) {
      // Create the first admin user
      const hashedPassword = await bcrypt.hash(password, 10);
      await prisma.user.create({
        data: {
          username,
          password: hashedPassword,
        },
      });
      await setSessionCookie();
      redirect("/admin");
    } else {
      return { error: "Geçersiz kullanıcı adı veya şifre" };
    }
  } else {
    // Normal DB login
    const user = await prisma.user.findUnique({
      where: { username },
    });

    if (user && await bcrypt.compare(password, user.password)) {
      await setSessionCookie();
      redirect("/admin");
    } else {
      return { error: "Geçersiz kullanıcı adı veya şifre" };
    }
  }
  
  // This redirect is inside if blocks but typescript requires a return here.
  return { error: "Bilinmeyen bir hata oluştu" };
}

async function setSessionCookie() {
  const cookieStore = await cookies();
  cookieStore.set("admin_session", "true", {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    maxAge: 60 * 60 * 24 * 7, // 1 week
    path: "/",
  });
}

export async function logout() {
  const cookieStore = await cookies();
  cookieStore.delete("admin_session");
  redirect("/admin/login");
}
