import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { getContractTemplateSections, updateContractTemplateAction } from "@/lib/actions/contractTemplates";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

export async function OPTIONS(request: NextRequest) {
  return corsPreflight(request);
}

export async function GET(request: NextRequest) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  if (!(await hasPermission("contract_templates"))) {
    return NextResponse.json({ error: "Keine Berechtigung." }, { status: 403, headers });
  }
  const [standard, tfp] = await Promise.all([getContractTemplateSections("standard"), getContractTemplateSections("tfp")]);
  return NextResponse.json({ standard, tfp }, { headers });
}

export async function POST(request: NextRequest) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const body = await request.json().catch(() => null);
  const type = body?.type === "tfp" ? "tfp" : "standard";
  const sections = Array.isArray(body?.sections) ? body.sections : [];

  const formData = new FormData();
  for (const s of sections) {
    formData.append("heading", typeof s?.heading === "string" ? s.heading : "");
    formData.append("body", typeof s?.body === "string" ? s.body : "");
    formData.append("appendix", s?.appendix ? "on" : "off");
  }
  await updateContractTemplateAction(type, formData);
  return NextResponse.json({ ok: true }, { headers });
}
