import Stripe from "stripe";

export const runtime = "nodejs";

const secretKey = process.env.STRIPE_SECRET_KEY;
if (!secretKey) throw new Error("Missing STRIPE_SECRET_KEY");

const stripe = new Stripe(secretKey);

export async function POST(req: Request) {
  try {
    const { amount, currency = "usd" } = await req.json();

    // basic validation
    const numericAmount = Number(amount);
    if (!numericAmount || numericAmount <= 0) {
      return Response.json({ error: "Invalid amount" }, { status: 400 });
    }

    // Stripe needs smallest unit (cents)
    const unitAmount = Math.round(numericAmount * 100);

    const appUrl = process.env.NEXT_PUBLIC_APP_URL;
    if (!appUrl) {
      return Response.json(
        { error: "Missing NEXT_PUBLIC_APP_URL" },
        { status: 500 },
      );
    }

    const session = await stripe.checkout.sessions.create({
      mode: "payment",
      line_items: [
        {
          price_data: {
            currency,
            unit_amount: unitAmount,
            product_data: {
              name: `Deposit ${numericAmount.toFixed(2)} ${currency.toUpperCase()}`,
            },
          },
          quantity: 1,
        },
      ],
      success_url: `${appUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${appUrl}/cancel`,
      metadata: {
        depositAmount: String(numericAmount),
        currency: currency.toUpperCase(),
      },
    });

    return Response.json({ url: session.url });
  } catch (err: any) {
    return Response.json(
      { error: err?.message ?? "Server error" },
      { status: 500 },
    );
  }
}
