import { NextRequest, NextResponse } from 'next/server';
import { getPaymentStatus } from '@/lib/myfatoorah';
import { prisma } from '@/lib/prisma';

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const paymentId = searchParams.get('paymentId');
    const orderId = searchParams.get('orderId');

    if (!paymentId || !orderId) {
      return NextResponse.redirect(new URL('/checkout?error=MissingParameters', req.url));
    }

    const statusObj = await getPaymentStatus(paymentId);
    
    if (statusObj.IsSuccess && statusObj.Data.InvoiceStatus === 'Paid') {
      await prisma.order.update({
        where: { id: orderId },
        data: {
          paymentStatus: 'paid',
          status: 'preparing'
        }
      });
      return NextResponse.redirect(new URL(`/account/orders/${orderId}?success=true`, req.url));
    } else {
      await prisma.order.update({
        where: { id: orderId },
        data: {
          paymentStatus: 'failed',
          status: 'cancelled'
        }
      });
      return NextResponse.redirect(new URL(`/checkout?error=PaymentFailed`, req.url));
    }
  } catch (err: any) {
    return NextResponse.redirect(new URL('/checkout?error=SystemError', req.url));
  }
}

export const dynamic = 'force-dynamic';
