import { NextRequest, NextResponse } from 'next/server';
import { logger } from '@/lib/logger';
import { stripe, retrievePaymentIntent } from '@/lib/stripe/server';
import { createClient } from '@/lib/supabase/server';
import { HTTP_STATUS_INTERNAL_SERVER_ERROR } from '@/lib/constants';

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

    if (!sessionId && !paymentIntentId) {
      return NextResponse.json({ error: 'Missing session_id or payment_intent parameter' }, { status: 400 });
    }

    // Authenticate user
    const supabase = await createClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // Handle Checkout Session verification
    if (sessionId) {
      const session = await stripe.checkout.sessions.retrieve(sessionId);
      
      return NextResponse.json({
        status: session.payment_status, // 'paid', 'unpaid', or 'no_payment_required'
        amount: session.amount_total,
        currency: session.currency,
      });
    }

    // Handle legacy PaymentIntent verification
    const paymentIntent = await retrievePaymentIntent(paymentIntentId!);

    return NextResponse.json({
      status: paymentIntent.status,
      amount: paymentIntent.amount,
      currency: paymentIntent.currency,
    });
  } catch (error) {
    logger.error('Payment verification error:', error);
    return NextResponse.json({ error: 'Failed to verify payment' }, { status: HTTP_STATUS_INTERNAL_SERVER_ERROR });
  }
}
