"use server";

import { revalidatePath } from "next/cache";
import { z } from "zod";
import { requireAdmin } from "@/lib/auth/admin-guard";
import { logAdminAction } from "@/lib/audit";
import { saveSiteSettings } from "@/lib/settings";

const schema = z.object({
  siteName: z.string().min(2).max(100),
  tagline: z.string().max(200),
  contactEmail: z.string().email().max(200),
  reviewSlaHours: z.coerce.number().int().min(1).max(720),
  applicationsOpen: z.enum(["on", ""]).transform((v) => v === "on"),
  maintenanceMode: z.enum(["on", ""]).transform((v) => v === "on"),
  maintenanceMessage: z.string().max(500),
  announcementBarEnabled: z.enum(["on", ""]).transform((v) => v === "on"),
  seoDefaultTitle: z.string().max(200).optional().default(""),
  seoTitleTemplate: z.string().max(200).optional().default(""),
  seoDefaultDescription: z.string().max(400).optional().default(""),
  seoKeywords: z.string().max(400).optional().default(""),
  seoOgImage: z.string().max(500).optional().default(""),
  seoTwitterHandle: z.string().max(100).optional().default(""),
  seoRobots: z.string().max(100).optional().default(""),
  maintenanceConfirm: z.string().optional().default(""),
});

export async function updateSiteSettings(formData: FormData): Promise<void> {
  const session = await requireAdmin();
  const adminId = (session.user as { id?: string }).id!;

  const parsed = schema.parse({
    siteName: formData.get("siteName"),
    tagline: formData.get("tagline") ?? "",
    contactEmail: formData.get("contactEmail"),
    reviewSlaHours: formData.get("reviewSlaHours") ?? "72",
    applicationsOpen: (formData.get("applicationsOpen") as string) ?? "",
    maintenanceMode: (formData.get("maintenanceMode") as string) ?? "",
    maintenanceMessage: formData.get("maintenanceMessage") ?? "",
    announcementBarEnabled:
      (formData.get("announcementBarEnabled") as string) ?? "",
    seoDefaultTitle: formData.get("seoDefaultTitle") ?? "",
    seoTitleTemplate: formData.get("seoTitleTemplate") ?? "",
    seoDefaultDescription: formData.get("seoDefaultDescription") ?? "",
    seoKeywords: formData.get("seoKeywords") ?? "",
    seoOgImage: formData.get("seoOgImage") ?? "",
    seoTwitterHandle: formData.get("seoTwitterHandle") ?? "",
    seoRobots: formData.get("seoRobots") ?? "",
    maintenanceConfirm: formData.get("maintenanceConfirm") ?? "",
  });

  if (parsed.maintenanceMode && parsed.maintenanceConfirm !== "ENABLE MAINTENANCE") {
    throw new Error(
      "Type ENABLE MAINTENANCE in the confirmation field to turn on maintenance mode.",
    );
  }

  const { maintenanceConfirm: _ignore, ...payload } = parsed;
  await saveSiteSettings(payload, adminId);

  await logAdminAction({
    adminUserId: adminId,
    action: "update_site_settings",
    metadata: payload,
  });

  revalidatePath("/admin/settings");
  revalidatePath("/");
}
