"use server";

import { getServerSession } from "next-auth";
import { revalidatePath } from "next/cache";
import { authOptions } from "@/lib/auth";
import { isAdminEmail } from "@/lib/admin";
import { emailService } from "@/lib/email/send";
import { auditLog } from "@/server/services/audit-log.service";

async function requireAdmin() {
  const session = await getServerSession(authOptions);
  if (!session?.user || !isAdminEmail(session.user.email)) {
    return null;
  }
  return session.user;
}

/** E5.2 — admin retry satu EmailJob yang gagal/antri, kirim ulang langsung. */
export async function retryEmailJobAction(jobId: string) {
  const admin = await requireAdmin();
  if (!admin) return { error: "Tidak memiliki akses admin" };
  if (!jobId) return { error: "jobId tidak valid" };

  const result = await emailService.retryJob(jobId);
  if (!result.ok) {
    return { error: result.error ?? "Gagal mengirim ulang email" };
  }
  await auditLog.record({
    admin: { id: admin.id, email: admin.email },
    action: "EMAIL_JOB_RETRY",
    entityType: "EmailJob",
    entityId: jobId,
  });
  revalidatePath("/admin/emails");
  revalidatePath("/admin/system");
  return { success: true as const };
}

/** E5.3 — admin resend email yang sudah pernah terkirim (mis. user lapor tidak terima). */
export async function resendEmailAction(emailSentId: string) {
  const admin = await requireAdmin();
  if (!admin) return { error: "Tidak memiliki akses admin" };
  if (!emailSentId) return { error: "emailSentId tidak valid" };

  const result = await emailService.resendEmail(emailSentId);
  if (!result.ok) {
    return { error: result.error ?? "Gagal mengirim ulang email" };
  }
  await auditLog.record({
    admin: { id: admin.id, email: admin.email },
    action: "EMAIL_RESEND",
    entityType: "EmailSent",
    entityId: emailSentId,
  });
  revalidatePath("/admin/emails");
  return { success: true as const };
}
