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

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

export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { id } = await params;
  const body = await request.json().catch(() => null);
  const formData = new FormData();
  formData.set("templateName", typeof body?.templateName === "string" ? body.templateName : "");
  formData.set("category", typeof body?.category === "string" ? body.category : "other");
  formData.set("body", typeof body?.body === "string" ? body.body : "");
  if (body?.includeLetterhead) formData.set("includeLetterhead", "on");
  if (body?.includeFooter) formData.set("includeFooter", "on");
  formData.set("footerText", typeof body?.footerText === "string" ? body.footerText : "");
  if (body?.includeRecipientAddress) formData.set("includeRecipientAddress", "on");
  formData.set("recipientAddress", typeof body?.recipientAddress === "string" ? body.recipientAddress : "");

  await updateGeneratedDocumentAction(id, formData);
  return NextResponse.json({ ok: true }, { headers });
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { id } = await params;
  await deleteGeneratedDocumentAction(id);
  return NextResponse.json({ ok: true }, { headers });
}
