import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { getAuthUser } from '@/lib/auth';
import { capturePaypalOrderAndFulfill } from '@/lib/paypal';

// POST /api/payments/paypal/capture-order
export async function POST(req: NextRequest) {
  try {
    await dbConnect();
    const body = await req.json();

    const {
      paypalOrderId,
      courseId,
      lessons = [],
      studentName,
      email,
      whatsappNumber,
      amount,
    } = body;

    if (!paypalOrderId || !courseId) {
      return NextResponse.json(
        { success: false, error: 'paypalOrderId and courseId are required for capture' },
        { status: 400 }
      );
    }

    const authUser = getAuthUser(req);

    // Capture payment with PayPal, create Order in database with status 'succeeded', & grant subscription
    const order = await capturePaypalOrderAndFulfill({
      paypalOrderId,
      studentId: authUser?.id,
      email: email || authUser?.email,
      studentName,
      whatsappNumber,
      courseId,
      lessons,
      amount: Number(amount),
    });

    return NextResponse.json({
      success: true,
      message: 'PayPal payment captured and course access granted successfully.',
      orderId: order._id.toString(),
      order,
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Failed to capture PayPal payment' },
      { status: 500 }
    );
  }
}
