"use server";

import { revalidatePath } from "next/cache";
import { prisma } from "@/lib/db";
import { requireAdmin } from "@/lib/admin-guard";
import { SECRET_PLACEHOLDER } from "./_constants";

export async function updateSettingsAction(category: string, formData: FormData) {
  const user = await requireAdmin();

  const updates: Array<{ key: string; value: string }> = [];
  for (const [key, raw] of formData.entries()) {
    if (typeof raw !== "string") continue;
    if (!key.startsWith(`${category}.`)) continue;

    // Skip secrets that are unchanged (sentinel value or empty)
    const existing = await prisma.setting.findUnique({
      where: { key },
      select: { isSecret: true, value: true },
    });
    if (existing?.isSecret) {
      if (raw === "" || raw === SECRET_PLACEHOLDER) continue;
    }
    if (existing && existing.value === raw) continue;
    updates.push({ key, value: raw });
  }

  if (updates.length === 0) {
    return { ok: true as const, updated: 0 };
  }

  await prisma.$transaction(
    updates.map((u) =>
      prisma.setting.update({
        where: { key: u.key },
        data: { value: u.value, updatedBy: user.id },
      }),
    ),
  );

  await prisma.auditLog.create({
    data: {
      actorId: user.id,
      actorName: user.name,
      actorEmail: user.email,
      source: "admin",
      action: `setting.update.${category}`,
      target: category,
      meta: { keys: updates.map((u) => u.key) } as never,
    },
  });

  revalidatePath(`/admin/${category === "site" ? "settings" : category}`);
  return { ok: true as const, updated: updates.length };
}
