import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import Stripe from "stripe";

const BLUEPRINT_PRICE_CENTS = 4700;
const CURRENCY = "eur";

function getStripe(): Stripe {
  const key = process.env.STRIPE_SECRET_KEY;
  if (!key) {
    throw new Error("STRIPE_SECRET_KEY is required");
  }
  return new Stripe(key);
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { email, businessName, placeId, locale } = body as {
      email: string;
      businessName: string;
      placeId: string;
      locale?: string;
    };

    if (!email || !businessName) {
      return NextResponse.json(
        { error: "Email and business name are required" },
        { status: 400 },
      );
    }

    const stripe = getStripe();
    const origin = request.headers.get("origin") || process.env.NEXT_PUBLIC_URL || "http://localhost:3000";
    const lang = locale || "en";

    const session = await stripe.checkout.sessions.create({
      mode: "payment",
      payment_method_types: ["card"],
      customer_email: email,
      line_items: [
        {
          price_data: {
            currency: CURRENCY,
            product_data: {
              name: "Reputation Blueprint",
              description: `Reputation Blueprint for ${businessName}`,
            },
            unit_amount: BLUEPRINT_PRICE_CENTS,
          },
          quantity: 1,
        },
      ],
      metadata: {
        product: "blueprint",
        business_name: businessName,
        place_id: placeId || "",
        email,
      },
      success_url: `${origin}/${lang}/get-started?step=success&session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${origin}/${lang}/get-started?step=payment`,
    });

    return NextResponse.json({ url: session.url });
  } catch (error) {
    console.error("Checkout error:", error);
    return NextResponse.json(
      { error: "Failed to create checkout session" },
      { status: 500 },
    );
  }
}
