import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { connectDB } from "@/lib/db";
import { Order } from "@/models/Order";
import { Client } from "@/models/Client";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { createTfpContractAction } from "@/lib/actions/admin";
import type { TfpContractData } from "@/models/Contract";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

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

export async function GET(request: NextRequest, { params }: { params: Promise<{ orderId: string }> }) {
  const headers = corsHeaders(request);
  const clientId = await getSessionClientId();
  if (!clientId || !(await isAdminSession()) || !(await hasPermission("orders_view"))) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  const { orderId } = await params;
  await connectDB();
  const order = await Order.findById(orderId).lean();
  if (!order) return NextResponse.json({ error: "Auftrag nicht gefunden." }, { status: 404, headers });
  const client = await Client.findById(order.clientId).select("billingStreet billingPostCode billingCity").lean();

  return NextResponse.json(
    {
      characterOrConcept: order.characterOrConcept,
      eventLocation: order.eventLocation,
      datePeriod: order.datePeriod,
      instagramHandle: order.instagramHandle,
      clientStreet: client?.billingStreet || "",
      clientPostCode: client?.billingPostCode || "",
      clientCity: client?.billingCity || "",
    },
    { headers }
  );
}

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 data = (await request.json().catch(() => null)) as TfpContractData | null;
  if (!data) return NextResponse.json({ error: "Ungültige Daten." }, { status: 400, headers });

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