// Server-side proxy for POST /seats/release on the passenger API.
//
// The browser calls THIS route (same-origin, /api/seats/release-hold) instead of the
// backend's public release endpoint directly. Route handlers run on the Next.js server, not
// in the browser, so the actual backend call — and its URL — never appears in client-side
// JS or network requests a user could copy and script against other travellers' holds.
// Keeping this indirection is the whole point: it doesn't add cryptographic protection (the
// backend endpoint is still public), it just keeps the release capability out of the
// browser's reach so it can't be trivially discovered and abused from client code.

const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:4000";

export async function POST(request: Request) {
  let holdId: string | undefined;
  try {
    ({ holdId } = await request.json());
  } catch {
    return Response.json({ message: "Invalid JSON body" }, { status: 400 });
  }

  if (!holdId || typeof holdId !== "string") {
    return Response.json({ message: "holdId is required" }, { status: 400 });
  }

  try {
    const backendResponse = await fetch(`${API_URL}/seats/release`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ holdId }),
    });

    const data = await backendResponse.json().catch(() => null);
    return Response.json(data, { status: backendResponse.status });
  } catch {
    return Response.json({ message: "Failed to reach booking service" }, { status: 502 });
  }
}
