"use server";

import { revalidatePath } from "next/cache";
import { prisma } from "@/lib/db";
import { requireAdmin } from "@/lib/admin-guard";
import { saveActiveSkin, isValidSkin, type SkinName } from "@/lib/theme";

export async function setActiveSkinAction(formData: FormData) {
  const user = await requireAdmin();
  const raw = String(formData.get("skin") ?? "");
  if (!isValidSkin(raw)) {
    return { ok: false as const, error: "Theme không hợp lệ." };
  }
  const skin: SkinName = raw;
  await saveActiveSkin(skin, user.id);

  await prisma.auditLog.create({
    data: {
      actorId: user.id,
      actorName: user.name,
      actorEmail: user.email,
      source: "admin",
      action: "theme.set_active",
      target: skin,
      meta: { skin } as never,
    },
  });

  // Layout reads the setting at request time; revalidate the whole tree so
  // the next render of any route picks up the new skin.
  revalidatePath("/", "layout");
  return { ok: true as const, skin };
}
