import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { updateTemplateAction, deleteTemplateAction } 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("name", typeof body?.name === "string" ? body.name : "");
  formData.set("category", typeof body?.category === "string" ? body.category : "other");
  formData.set("body", typeof body?.body === "string" ? body.body : "");
  if (body?.defaultIncludeLetterhead) formData.set("defaultIncludeLetterhead", "on");
  if (body?.defaultIncludeFooter) formData.set("defaultIncludeFooter", "on");
  formData.set("defaultFooterText", typeof body?.defaultFooterText === "string" ? body.defaultFooterText : "");
  if (body?.defaultIncludeRecipientAddress) formData.set("defaultIncludeRecipientAddress", "on");

  await updateTemplateAction(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 deleteTemplateAction(id);
  return NextResponse.json({ ok: true }, { headers });
}
