import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { createStandardContractAction, sendContractAction, deleteContractAction } from "@/lib/actions/admin";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

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

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 === "send") {
    const contractId = typeof body?.contractId === "string" ? body.contractId : "";
    if (!contractId) return NextResponse.json({ error: "Kein Vertrag angegeben." }, { status: 400, headers });
    await sendContractAction(contractId);
    return NextResponse.json({ ok: true }, { headers });
  }

  if (body?.action === "delete") {
    const contractId = typeof body?.contractId === "string" ? body.contractId : "";
    if (!contractId) return NextResponse.json({ error: "Kein Vertrag angegeben." }, { status: 400, headers });
    await deleteContractAction(contractId);
    return NextResponse.json({ ok: true }, { headers });
  }

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