import { events } from "../../../lib/data";

export async function POST(request: Request) {
  try {
    const { eventSlug, tierName, quantity } = (await request.json()) as {
      eventSlug?: string;
      tierName?: string;
      quantity?: number;
    };
    const event = events.find((candidate) => candidate.slug === eventSlug);
    const tier = event?.tickets.find((candidate) => candidate.name === tierName);

    if (
      !event ||
      !tier ||
      !Number.isInteger(quantity) ||
      quantity! < 1 ||
      quantity! > 8
    ) {
      return Response.json(
        { error: "Invalid event, ticket or quantity." },
        { status: 400 },
      );
    }
    if (tier.remaining < quantity!) {
      return Response.json(
        { error: "Not enough tickets remain." },
        { status: 409 },
      );
    }

    const secret = process.env.STRIPE_SECRET_KEY;
    if (process.env.PAYMENTS_ENABLED !== "true" || !secret) {
      return Response.json(
        {
          message:
            "The storefront is ready. Complete the production payment checklist, add Stripe secrets, and explicitly enable payments before accepting orders.",
        },
        { status: 503 },
      );
    }

    const orderId = crypto.randomUUID();
    const origin = new URL(request.url).origin;
    const totalPrice = Math.round(tier.price * 100);
    const fee = Math.round(tier.fee * 100);
    const form = new URLSearchParams();

    form.set("mode", "payment");
    form.set(
      "success_url",
      `${origin}/dashboard/buyer?checkout=success&session_id={CHECKOUT_SESSION_ID}`,
    );
    form.set("cancel_url", `${origin}/event/${event.slug}?checkout=cancelled`);
    form.set("client_reference_id", orderId);
    form.set("metadata[order_id]", orderId);
    form.set("metadata[event_slug]", event.slug);
    form.set("payment_intent_data[transfer_group]", `ORDER_${orderId}`);
    form.set("line_items[0][price_data][currency]", "usd");
    form.set(
      "line_items[0][price_data][product_data][name]",
      `${event.title} — ${tier.name}`,
    );
    form.set(
      "line_items[0][price_data][product_data][description]",
      `${event.date} · ${event.venue}`,
    );
    form.set(
      "line_items[0][price_data][unit_amount]",
      String(totalPrice),
    );
    form.set("line_items[0][quantity]", String(quantity));
    form.set("line_items[1][price_data][currency]", "usd");
    form.set(
      "line_items[1][price_data][product_data][name]",
      "EasyPay Tickets service fee",
    );
    form.set("line_items[1][price_data][unit_amount]", String(fee));
    form.set("line_items[1][quantity]", String(quantity));

    const response = await fetch("https://api.stripe.com/v1/checkout/sessions", {
      method: "POST",
      headers: {
        authorization: `Bearer ${secret}`,
        "content-type": "application/x-www-form-urlencoded",
        "idempotency-key": `checkout_${orderId}`,
      },
      body: form,
    });
    const data = (await response.json()) as {
      url?: string;
      error?: { message?: string };
    };
    if (!response.ok || !data.url) {
      return Response.json(
        { error: data.error?.message || "Stripe checkout could not be created." },
        { status: 502 },
      );
    }
    return Response.json({ url: data.url });
  } catch {
    return Response.json(
      { error: "Unable to start checkout." },
      { status: 500 },
    );
  }
}
