import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { getAuthUser } from '@/lib/auth';
import { Course } from '@/models/Course';
import { Student } from '@/models/Student';
import { getStripeInstance } from '@/lib/stripe';

// POST /api/payments/create-checkout-session
// Creates an official Stripe Hosted Checkout Session and returns redirect URL.
// NOTE: Order is NOT created in database upfront to prevent abandoned/pending order clutter.
// Order is created ONLY after successful payment confirmation!
export async function POST(req: NextRequest) {
  try {
    await dbConnect();
    const body = await req.json();

    const {
      courseId,
      lessons = [],
      studentName,
      email,
      whatsappNumber,
      country,
      amount: providedAmount,
    } = body;

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

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

    // Determine target Student record
    const authUser = getAuthUser(req);
    let targetStudentId = authUser?.id;

    if (!targetStudentId) {
      if (!email) {
        return NextResponse.json(
          { success: false, error: 'Student email is required for checkout' },
          { status: 400 }
        );
      }

      const existingStudent = await Student.findOne({ email: email.toLowerCase().trim() });
      if (existingStudent) {
        targetStudentId = existingStudent._id.toString();
        if (studentName && existingStudent.name !== studentName) {
          existingStudent.name = studentName;
          await existingStudent.save();
        }
      } else {
        const newStudent = await Student.create({
          name: studentName || email.split('@')[0],
          email: email.toLowerCase().trim(),
          password: `Student@${Math.floor(100000 + Math.random() * 900000)}`,
          phoneNumber: whatsappNumber || '',
          status: 'active',
        });
        targetStudentId = newStudent._id.toString();
      }
    }

    // Calculate final payable amount
    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 }
      );
    }

    // Get dynamic Stripe SDK instance resolved from Database Settings table
    const { stripe, config } = await getStripeInstance();

    if (!config.isEnabled) {
      return NextResponse.json(
        { success: false, error: 'Stripe payment gateway is currently disabled in system settings' },
        { status: 400 }
      );
    }

    const origin = req.headers.get('origin') || process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';

    // Create official Stripe Hosted Checkout Session
    // Order will be created in MongoDB AFTER payment is verified paid!
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ['card'],
      line_items: [
        {
          price_data: {
            currency: 'eur',
            product_data: {
              name: targetCourse.title,
              description: `ApkaGermanSchool Course Access (${targetCourse.level || 'German Course'})`,
            },
            unit_amount: Math.round(finalAmount * 100),
          },
          quantity: 1,
        },
      ],
      mode: 'payment',
      customer_email: email || authUser?.email,
      success_url: `${origin}/student/purchases?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${origin}/`,
      metadata: {
        courseId: targetCourse._id.toString(),
        studentId: String(targetStudentId),
        lessons: JSON.stringify(selectedLessonsArray),
        amount: String(finalAmount),
      },
    });

    return NextResponse.json({
      success: true,
      url: session.url,
      sessionId: session.id,
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Failed to create Stripe Checkout Session' },
      { status: 500 }
    );
  }
}
