import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { generateDocumentAction } from "@/lib/actions/documents";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

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

// Erzeugt ein echtes, personenbezogenes Dokument (Vertrag/Zeugnis/etc.) —
// der Renderer verlangt vorher eine erfolgreiche /verify-password-Bestätigung.
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 formData = new FormData();
  formData.set("category", typeof body?.category === "string" ? body.category : "other");
  formData.set("templateName", typeof body?.templateName === "string" ? body.templateName : "");
  formData.set("body", typeof body?.body === "string" ? body.body : "");
  if (body?.templateId) formData.set("templateId", body.templateId);
  if (body?.clientId) formData.set("clientId", body.clientId);

  const result = await generateDocumentAction({}, formData);
  if (result.error) return NextResponse.json({ error: result.error }, { status: 400, headers });
  return NextResponse.json({ ok: true, documentId: result.documentId }, { headers });
}
