import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { Course } from '@/models/Course';
import { createPaypalOrder } from '@/lib/paypal';

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

    const { courseId, lessons = [], amount: providedAmount } = body;

    if (!courseId) {
      return NextResponse.json(
        { success: false, error: 'courseId is required to create a PayPal order' },
        { status: 400 }
      );
    }

    const targetCourse = await Course.findById(courseId);
    if (!targetCourse) {
      return NextResponse.json(
        { success: false, error: 'Selected course was not found' },
        { status: 404 }
      );
    }

    let calculatedAmount = 0;
    const selectedLessonsArray = Array.isArray(lessons) ? lessons : [];

    if (selectedLessonsArray.length > 0) {
      const { Lesson } = await import('@/models/Lesson');
      const foundLessons = await Lesson.find({ _id: { $in: selectedLessonsArray } });
      foundLessons.forEach((l) => {
        calculatedAmount += l.price || 0;
      });
    } else {
      calculatedAmount =
        targetCourse.offerPrice !== undefined && targetCourse.offerPrice !== null
          ? targetCourse.offerPrice
          : targetCourse.regularPrice;
    }

    const finalAmount =
      providedAmount !== undefined && providedAmount !== null && providedAmount !== ''
        ? Number(providedAmount)
        : calculatedAmount;

    if (isNaN(finalAmount) || finalAmount <= 0) {
      return NextResponse.json(
        { success: false, error: 'Invalid order amount' },
        { status: 400 }
      );
    }

    // Create PayPal Checkout order via PayPal REST API
    const result = await createPaypalOrder({
      amount: finalAmount,
      currency: 'EUR',
      courseTitle: targetCourse.title,
    });

    return NextResponse.json({
      success: true,
      paypalOrderId: result.paypalOrderId,
      clientId: result.clientId,
      mode: result.mode,
      amount: finalAmount,
      currency: 'EUR',
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Failed to create PayPal checkout order' },
      { status: 500 }
    );
  }
}
