import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession, hasPermission } from "@/lib/adminAuth";
import { getOrderDetail } from "@/lib/orderDetail";
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())) {
    return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401, headers });
  }
  if (!(await hasPermission("orders_view"))) {
    return NextResponse.json({ error: "Keine Berechtigung." }, { status: 403, headers });
  }

  const { orderId } = await params;
  const detail = await getOrderDetail(orderId);
  if (!detail) return NextResponse.json({ error: "Auftrag nicht gefunden." }, { status: 404, headers });

  return NextResponse.json(detail, { headers });
}
