export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { headers } from 'next/headers';

const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
const STRIPE_API_VERSION = '2024-12-18.acacia';

export async function POST(request: NextRequest) {
  if (!STRIPE_SECRET_KEY) {
    return NextResponse.json(
      { error: 'Stripe is not configured.' },
      { status: 500 }
    );
  }

  try {
    const headersList = await headers();
    const origin = headersList.get('origin')
      || (headersList.get('x-forwarded-host')
        ? `https://${headersList.get('x-forwarded-host')}`
        : process.env.NEXTAUTH_URL || 'http://localhost:3000');

    // Create Stripe Checkout Session for $197 AI Scope
    const stripeResponse = await fetch('https://api.stripe.com/v1/checkout/sessions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${STRIPE_SECRET_KEY}`,
        'Content-Type': 'application/x-www-form-urlencoded',
        'Stripe-Version': STRIPE_API_VERSION,
      },
      body: new URLSearchParams({
        'mode': 'payment',
        'success_url': `${origin}/services/ai-scope/intake?session_id={CHECKOUT_SESSION_ID}`,
        'cancel_url': `${origin}/services/ai-scope`,
        'line_items[0][price_data][currency]': 'usd',
        'line_items[0][price_data][product_data][name]': 'AI Project Scoping',
        'line_items[0][price_data][product_data][description]': 'Professional AI-powered project scope document including data models, architecture diagrams, cost estimates, and branded PDF deliverable.',
        'line_items[0][price_data][unit_amount]': '19700',
        'line_items[0][quantity]': '1',
        'metadata[service]': 'ai-scope',
        'payment_intent_data[metadata][service]': 'ai-scope',
      }),
    });

    if (!stripeResponse.ok) {
      const errorData = await stripeResponse.json();
      console.error('Stripe checkout error:', errorData);
      return NextResponse.json(
        { error: 'Failed to create checkout session', details: errorData.error?.message },
        { status: 500 }
      );
    }

    const session = await stripeResponse.json();

    return NextResponse.json({
      sessionId: session.id,
      sessionUrl: session.url,
    });
  } catch (error) {
    console.error('AI Scope checkout error:', error);
    return NextResponse.json(
      { error: 'Failed to create checkout session' },
      { status: 500 }
    );
  }
}
