"use server";

import { getServerSession } from "next-auth";
import { revalidatePath } from "next/cache";
import { authOptions } from "@/lib/auth";
import { isAdminEmail } from "@/lib/admin";
import { organizerService } from "@/server/services/organizer.service";
import { submitVerificationSchema, reviewVerificationSchema } from "./schemas";

export async function submitVerificationAction(formData: FormData) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return { error: "Kamu harus login terlebih dahulu" };
  }

  const raw = {
    fullName: formData.get("fullName") as string,
    nik: formData.get("nik") as string,
    birthDate: formData.get("birthDate") as string,
    address: formData.get("address") as string,
    ktpImageKey: formData.get("ktpImageKey") as string,
    livenessKey: formData.get("livenessKey") as string,
    bankName: formData.get("bankName") as string,
    bankAccountNumber: formData.get("bankAccountNumber") as string,
    bankAccountName: formData.get("bankAccountName") as string,
  };

  const result = submitVerificationSchema.safeParse(raw);
  if (!result.success) {
    return { error: result.error.issues[0].message };
  }

  try {
    await organizerService.submitVerification(session.user.id, {
      ...result.data,
      birthDate: new Date(result.data.birthDate),
    });
    revalidatePath("/verify");
    revalidatePath("/profile");
    revalidatePath("/admin/verifications");
    return { success: true };
  } catch (err) {
    return { error: (err as Error).message };
  }
}

export async function reviewVerificationAction(formData: FormData) {
  const session = await getServerSession(authOptions);
  if (!session?.user || !isAdminEmail(session.user.email)) {
    return { error: "Tidak memiliki akses admin" };
  }

  const raw = {
    verificationId: formData.get("verificationId") as string,
    decision: formData.get("decision") as string,
    rejectionReason: (formData.get("rejectionReason") as string) || undefined,
  };

  const result = reviewVerificationSchema.safeParse(raw);
  if (!result.success) {
    return { error: result.error.issues[0].message };
  }

  try {
    await organizerService.reviewVerification({
      verificationId: result.data.verificationId,
      decision: result.data.decision,
      rejectionReason: result.data.rejectionReason,
      reviewerId: session.user.id,
    });
    revalidatePath("/admin/verifications");
    revalidatePath("/verify");
    revalidatePath("/profile");
    return { success: true };
  } catch (err) {
    return { error: (err as Error).message };
  }
}
