export const dynamic = 'force-dynamic';

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

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

export async function GET(request: NextRequest) {
  const sessionId = request.nextUrl.searchParams.get('session_id');

  if (!sessionId || !STRIPE_SECRET_KEY) {
    return NextResponse.json({ verified: false, error: 'Invalid session or configuration.' });
  }

  try {
    // Retrieve the Stripe Checkout Session
    const res = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, {
      headers: {
        'Authorization': `Bearer ${STRIPE_SECRET_KEY}`,
        'Stripe-Version': STRIPE_API_VERSION,
      },
    });

    if (!res.ok) {
      return NextResponse.json({ verified: false, error: 'Could not retrieve session.' });
    }

    const session = await res.json();

    // Verify this is an ai-scope payment and it's paid
    if (session.payment_status === 'paid' && session.metadata?.service === 'ai-scope') {
      return NextResponse.json({
        verified: true,
        customerEmail: session.customer_details?.email || session.customer_email || '',
        customerName: session.customer_details?.name || '',
      });
    }

    return NextResponse.json({ verified: false, error: 'Payment not completed or invalid service.' });
  } catch (error) {
    console.error('Verify error:', error);
    return NextResponse.json({ verified: false, error: 'Verification failed.' });
  }
}
