import { decideCuratedDomain } from "../../../db/curatedDomains";

/**
 * PATCH /api/admin/curated-domains/[id]
 *
 * Admin entscheidet über einen User-Vorschlag für die Country-Curated-Liste.
 *
 * Body: { decision: "approved" | "rejected", note?: string }
 *
 * Bei "approved": Domain wird sofort von GET /api/protection/webcontent-domains
 * zurückgegeben (kein Deploy nötig — Live-Query auf CuratedDomain).
 * Bei "rejected": Domain verschwindet aus der Inbox.
 */
export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig();
  const adminSecret = getHeader(event, "x-admin-secret");
  if (adminSecret !== config.adminSecret) {
    throw createError({ statusCode: 401, message: "Unauthorized" });
  }

  const id = getRouterParam(event, "id");
  if (!id) throw createError({ statusCode: 400, data: { error: "MISSING_ID" } });

  const body = await readBody(event).catch(() => ({}));
  const decision = body?.decision as string;
  const note = body?.note as string | undefined;

  if (decision !== "approved" && decision !== "rejected") {
    throw createError({
      statusCode: 400,
      data: { error: "INVALID_DECISION", valid: ["approved", "rejected"] },
    });
  }

  try {
    const result = await decideCuratedDomain(id, decision, note);
    return { ok: true, ...result };
  } catch (err: any) {
    if (err.code === "NOT_FOUND") {
      throw createError({ statusCode: 404, data: { error: "CURATED_DOMAIN_NOT_FOUND" } });
    }
    if (err.code === "ALREADY_DECIDED") {
      throw createError({
        statusCode: 409,
        data: { error: "ALREADY_DECIDED", currentStatus: err.currentStatus },
      });
    }
    throw createError({ statusCode: 500, message: err.message ?? "Unbekannter Fehler" });
  }
});
