import { catalogEntryForTier, isCheckoutConfigurationComplete } from "@/lib/commerce";

export async function POST(request: Request) {
  if (process.env.CHECKOUT_OPEN !== "true") {
    return Response.json({ error: "A venda ainda não está aberta." }, { status: 503 });
  }
  const secret = process.env.STRIPE_SECRET_KEY;
  const baseUrl = process.env.PUBLIC_BASE_URL;
  if (!secret || !baseUrl || !isCheckoutConfigurationComplete()) return Response.json({ error: "Checkout indisponível por configuração incompleta." }, { status: 503 });
  const origin = request.headers.get("origin");
  if (origin && new URL(baseUrl).origin !== origin) return Response.json({ error: "Origem não autorizada." }, { status: 403 });

  try {
    const payload = (await request.json()) as { ticketTier?: unknown; termsAccepted?: unknown; dataConfirmed?: unknown };
    const ticketTier = typeof payload.ticketTier === "string" ? payload.ticketTier : "";
    const catalogEntry = catalogEntryForTier(ticketTier);
    if (!catalogEntry || payload.termsAccepted !== true || payload.dataConfirmed !== true) {
      return Response.json({ error: "Confirme o bilhete e os termos antes de continuar." }, { status: 400 });
    }
    const publicOrderId = crypto.randomUUID();
    const parameters = new URLSearchParams({
      mode: "payment",
      "automatic_payment_methods[enabled]": "true",
      "line_items[0][price]": catalogEntry.priceId,
      "line_items[0][quantity]": "1",
      success_url: `${baseUrl}/confirmacao?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${baseUrl}/checkout/recuperar`,
      client_reference_id: publicOrderId,
      "metadata[order_public_id]": publicOrderId,
      "metadata[ticket_tier]": ticketTier,
      "payment_intent_data[metadata][order_public_id]": publicOrderId,
      "payment_intent_data[metadata][ticket_tier]": ticketTier,
      "consent_collection[terms_of_service]": "required",
    });
    const stripeResponse = await fetch("https://api.stripe.com/v1/checkout/sessions", {
      method: "POST",
      headers: { authorization: `Bearer ${secret}`, "content-type": "application/x-www-form-urlencoded", "idempotency-key": publicOrderId },
      body: parameters,
    });
    const session = (await stripeResponse.json()) as { id?: string; url?: string; error?: { message?: string } };
    if (!stripeResponse.ok || !session.id || !session.url) {
      console.error("stripe_session_failed", session.error?.message || stripeResponse.status);
      return Response.json({ error: "Não foi possível iniciar o pagamento em segurança." }, { status: 502 });
    }
    return Response.json({ sessionId: session.id, url: session.url }, { status: 201 });
  } catch (error) {
    console.error("checkout_start_failed", error);
    return Response.json({ error: "Não foi possível iniciar o checkout." }, { status: 500 });
  }
}
