import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { toggleChecklistItemAction, addChecklistItemAction, deleteChecklistItemAction } from "@/lib/actions/orderChecklist";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

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

// Ein Endpoint für alle drei Checklisten-Aktionen (statt drei Routen) — die
// App schickt jeweils, welche Aktion gemeint ist, alle drei rufen dieselben
// bestehenden Server Actions (src/lib/actions/orderChecklist.ts) auf.
export async function POST(request: NextRequest, { params }: { params: Promise<{ orderId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { orderId } = await params;
  const body = await request.json().catch(() => null);

  if (body?.action === "add" && typeof body.text === "string") {
    await addChecklistItemAction(orderId, body.text);
  } else if (body?.action === "toggle" && typeof body.itemId === "string" && typeof body.done === "boolean") {
    await toggleChecklistItemAction(orderId, body.itemId, body.done);
  } else if (body?.action === "delete" && typeof body.itemId === "string") {
    await deleteChecklistItemAction(orderId, body.itemId);
  } else {
    return NextResponse.json({ error: "Ungültige Anfrage." }, { status: 400, headers });
  }

  return NextResponse.json({ ok: true }, { headers });
}
