import { NextResponse } from "next/server";
import { getSessionCustomer, getCustomerOrderDetail } from "../../../lib/customerAuth";

// Polled by /checkout/verarbeitung after a Payment Element redirect
// returns — see spicy-leaping-pizza.md §3. Requires the customer's own
// session (checkout is "Konto Pflicht", so one always exists by the time
// this page is reachable) rather than accepting a bare orderNumber, so a
// guessed/leaked order number can't be used to probe another customer's
// payment status.
export async function GET(request: Request) {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ ok: false, reason: "Bitte zuerst einloggen." }, { status: 401 });

  const orderNumber = new URL(request.url).searchParams.get("orderNumber");
  if (!orderNumber) return NextResponse.json({ ok: false, reason: "orderNumber fehlt." }, { status: 400 });

  const order = await getCustomerOrderDetail(session.token, session.customer.id, orderNumber);
  if (!order) return NextResponse.json({ ok: false, reason: "Bestellung nicht gefunden." }, { status: 404 });

  return NextResponse.json({
    ok: true,
    status: order.status,
    paymentStatus: order.paymentStatus,
    // Refined from the checkout-time "Online-Zahlung" placeholder to the
    // actual instrument (Kreditkarte/PayPal) once confirm-payment sets it
    // — see resolveStripePaymentMethodLabel's own comment. Returned here
    // so VerarbeitungContent can patch the pending sessionStorage snapshot
    // before promoting it, so /bestellbestaetigung shows the real one.
    paymentMethodTitle: order.paymentMethodTitle,
  });
}
