import { NextResponse } from "next/server";
import { calculateTotal } from "@/lib/payment";
import { validatePayment } from "@/lib/payment";
import { ticketTiers } from "@/content/tickets";

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const result = validatePayment(body);

    if (!result.ok) {
      return NextResponse.json({ ok: false, error: result.error }, { status: 400 });
    }

    const tier = ticketTiers.find((t) => t.id === result.data.ticketId)!;
    const totalUsd = calculateTotal(result.data.ticketId, result.data.quantity);

    const record = {
      ...result.data,
      ticketName: tier.name,
      totalUsd,
      status: "pending",
      note: "v1 stub — wire payment provider (Stripe/Chapa) in production",
    };

    console.info("[GRV Summit Payment]", JSON.stringify(record, null, 2));

    return NextResponse.json({
      ok: true,
      orderId: `GRV-${Date.now()}`,
      totalUsd,
      paymentMethod: result.data.paymentMethod,
    });
  } catch {
    return NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 });
  }
}
