import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { setOrderShootDateAction } 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);
  const value = typeof body?.value === "string" ? body.value : "";
  const endValue = typeof body?.endValue === "string" ? body.endValue : "";
  const confirmLeadTimeOverride = Boolean(body?.confirmLeadTimeOverride);
  const eventAddress = {
    street: typeof body?.street === "string" ? body.street : "",
    postCode: typeof body?.postCode === "string" ? body.postCode : "",
    city: typeof body?.city === "string" ? body.city : "",
    countryCode: typeof body?.countryCode === "string" ? body.countryCode : "DE",
    note: typeof body?.addressNote === "string" ? body.addressNote : "",
  };

  const result = await setOrderShootDateAction(orderId, value, endValue, eventAddress, confirmLeadTimeOverride);
  return NextResponse.json(result, { headers });
}
