import { NextResponse } from "next/server";

const STRIPE_KEY = process.env.STRIPE_SECRET_KEY || "";

const PLANS: Record<string, { name: string; price: number; currency: string }> = {
  "starter-setup": { name: "AI Chat Setup", price: 90000, currency: "eur" },
  "starter-monthly": { name: "AI Chat Monthly", price: 29900, currency: "eur" },
  "site-setup": { name: "Smart Site Setup", price: 350000, currency: "eur" },
  "site-monthly": { name: "Smart Site Monthly", price: 74900, currency: "eur" },
  "growth-setup": { name: "AI Growth Setup", price: 500000, currency: "eur" },
  "growth-monthly": { name: "AI Growth Monthly", price: 195000, currency: "eur" },
  "demo-real-estate-essential": { name: "Real Estate Essential", price: 39000, currency: "eur" },
  "demo-real-estate-profesional": { name: "Real Estate Professional", price: 79000, currency: "eur" },
  "demo-real-estate-premium": { name: "Real Estate Premium", price: 139000, currency: "eur" },
  "demo-restaurant-essential": { name: "Restaurant Essential", price: 39000, currency: "eur" },
  "demo-restaurant-profesional": { name: "Restaurant Professional", price: 79000, currency: "eur" },
  "demo-restaurant-premium": { name: "Restaurant Premium", price: 139000, currency: "eur" },
  "demo-clinic-essential": { name: "Clinic Essential", price: 39000, currency: "eur" },
  "demo-clinic-profesional": { name: "Clinic Professional", price: 79000, currency: "eur" },
  "demo-clinic-premium": { name: "Clinic Premium", price: 139000, currency: "eur" },
  "demo-home-services-essential": { name: "Home Services Essential", price: 39000, currency: "eur" },
  "demo-home-services-profesional": { name: "Home Services Professional", price: 79000, currency: "eur" },
  "demo-home-services-premium": { name: "Home Services Premium", price: 139000, currency: "eur" },
};

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { planId, email, name, planType = "monthly" } = body;

    const origin = request.headers.get("origin") || "http://45.95.42.114:1284";

    let planKey = planId;
    if (!planId.startsWith("demo-") && !PLANS[planId]) {
      planKey = `${planId}-${planType}`;
    }
    
    const plan = PLANS[planKey];

    if (!plan) {
      return NextResponse.json({ error: "Invalid plan selected" }, { status: 400 });
    }

    const params = new URLSearchParams();
    params.append("payment_method_types[]", "card");
    params.append("line_items[0][price_data][currency]", plan.currency);
    params.append("line_items[0][price_data][product_data][name]", plan.name);
    params.append("line_items[0][price_data][product_data][description]", `SiteMente - ${plan.name}`);
    params.append("line_items[0][price_data][unit_amount]", String(plan.price));
    params.append("line_items[0][quantity]", "1");
    params.append("mode", planType === "monthly" ? "subscription" : "payment");
    params.append("customer_email", email || "");
    params.append("metadata[customerName]", name || "");
    params.append("metadata[planId]", planId);
    params.append("metadata[planType]", planType);
    params.append("success_url", `${origin}/success?session_id={CHECKOUT_SESSION_ID}`);
    params.append("cancel_url", `${origin}/?cancelled=true`);

    if (planType === "monthly") {
      params.append("line_items[0][price_data][recurring][interval]", "month");
    }

    const response = await fetch("https://api.stripe.com/v1/checkout/sessions", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${STRIPE_KEY}`,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: params.toString(),
    });

    const session = await response.json();

    if (session.error) {
      return NextResponse.json({ error: session.error.message }, { status: 400 });
    }

    return NextResponse.json({ sessionId: session.id, url: session.url });
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : "Failed to create checkout session";
    console.error("Stripe error:", message);
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
