import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getSessionClientId } from "@/lib/auth";
import { isAdminSession } from "@/lib/adminAuth";
import { adminProposePriceAction, adminRespondPriceAction } 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 === "respond") {
    const decision = body?.decision === "accepted" ? "accepted" : "rejected";
    await adminRespondPriceAction(orderId, decision);
    return NextResponse.json({ ok: true }, { headers });
  }

  const amount = Number(body?.amount);
  if (!Number.isFinite(amount) || amount <= 0) return NextResponse.json({ error: "Bitte einen gültigen Betrag angeben." }, { status: 400, headers });
  const note = typeof body?.note === "string" ? body.note : "";
  await adminProposePriceAction(orderId, amount, note);
  return NextResponse.json({ ok: true }, { headers });
}
