import { NextResponse } from 'next/server';
// import { stripe } from '@/lib/stripe';
import Stripe from 'stripe';

export async function POST(req: Request) {
  const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
          apiVersion: '2024-04-10',
        });

  try {
    const { priceId, email,  name, address } = await req.json();

    // 1️⃣ Create customer (or fetch existing)
    const customer = await stripe.customers.create({
      email: email || 'testuser@example.com',
      name, 
      address, 
    });

    // 2️⃣ Create subscription
    const subscription = await stripe.subscriptions.create({
      customer: customer.id,
      items: [{ price: priceId }],
      payment_behavior: 'default_incomplete',
      expand: ['latest_invoice.payment_intent'],
      metadata: { user: 'demo-user' },
    });

    const clientSecret = (subscription.latest_invoice as any).payment_intent.client_secret;

    return NextResponse.json({
      clientSecret,
      subscriptionId: subscription.id,
      customerId: customer.id,
    });
  } catch (err: any) {
    console.error('Error creating subscription:', err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}