import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { stripe } from '@/lib/stripe';
import { getOrCreateStripeCustomer } from '@/lib/billing-service';

/**
 * POST /api/billing/setup-intent
 * Creates a Stripe SetupIntent so the client can save a payment method.
 * Returns { clientSecret, customerId }.
 */
export async function POST(request: NextRequest) {
  const accessToken = request.cookies.get('scriba.access_token')?.value;
  const session = await getSession(accessToken);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  try {
    const customerId = await getOrCreateStripeCustomer(
      session.user.id,
      session.user.email,
      session.user.name,
    );

    const setupIntent = await stripe.setupIntents.create({
      customer: customerId,
      automatic_payment_methods: { enabled: true },
      usage: 'off_session',
    });

    return NextResponse.json({ clientSecret: setupIntent.client_secret, customerId });
  } catch (err) {
    console.error('SetupIntent error:', err);
    return NextResponse.json({ error: 'Failed to create setup intent' }, { status: 500 });
  }
}
