"use server";

import bcrypt from "bcryptjs";
import { redirect } from "next/navigation";
import { LoginSchema, type ActionState } from "@/app/lib/definitions";
import { createSession, deleteSession } from "@/app/lib/session";
import { getOptionalSession } from "@/app/lib/dal";

export async function login(
  _prevState: ActionState | undefined,
  formData: FormData,
): Promise<ActionState> {
  const validated = LoginSchema.safeParse({
    email: formData.get("email"),
    password: formData.get("password"),
  });

  if (!validated.success) {
    return {
      errors: validated.error.flatten().fieldErrors,
      message: "Please fix the errors below.",
    };
  }

  const adminEmail = process.env.ADMIN_EMAIL;
  const passwordHash = process.env.ADMIN_PASSWORD_HASH;

  if (!adminEmail || !passwordHash) {
    return {
      message: "Admin credentials are not configured on the server.",
    };
  }

  const { email, password } = validated.data;
  const emailMatches = email.toLowerCase() === adminEmail.toLowerCase();
  const passwordMatches = await bcrypt.compare(password, passwordHash);

  if (!emailMatches || !passwordMatches) {
    return { message: "Invalid email or password." };
  }

  await createSession(adminEmail);
  redirect("/admin");
}

export async function logout() {
  await deleteSession();
  redirect("/admin/login");
}

export async function requireAdmin() {
  const session = await getOptionalSession();
  if (!session) {
    redirect("/admin/login");
  }
  return session;
}
