import { NextResponse } from "next/server";
import { getToken } from "@/lib/session";

const API_URL = process.env.NEXT_PUBLIC_API_URL;

/**
 * Thin proxy to Laravel POST /checkout. Unlike the auth endpoints, this
 * doesn't mint a new token — it just forwards the existing httpOnly-cookie
 * Bearer token (server-side only, never exposed to client JS) so the
 * CheckoutForm client component can submit without touching the token itself.
 */
export async function POST(request: Request) {
  const token = await getToken();

  if (!token) {
    return NextResponse.json({ message: "You must log in first." }, { status: 401 });
  }

  const body = await request.json();

  const apiRes = await fetch(`${API_URL}/checkout`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify(body),
  });

  const data = await apiRes.json();

  return NextResponse.json(data, { status: apiRes.status });
}
