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

// POST /api/payments/create-intent
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 a payment intent' },
        { 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 registration' },
          { 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 {
        // Auto-create student account for guest purchase
        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 }
      );
    }

    // Step 1: Create local pending Order record
    const pendingOrder = await Order.create({
      student: targetStudentId,
      courseId: targetCourse._id,
      lessons: selectedLessonsArray,
      gateway: 'stripe',
      amount: finalAmount,
      currency: 'EUR',
      status: 'pending',
      paymentRequired: true,
      initiatedAt: new Date(),
    });

    // Step 2: Initialize Stripe PaymentIntent
    // Note: Stripe amounts are in cents/smallest currency unit (e.g. 50.00 EUR = 5000 cents)
    const amountInCents = Math.round(finalAmount * 100);

    const paymentIntent = await stripe.paymentIntents.create({
      amount: amountInCents,
      currency: 'eur',
      metadata: {
        orderId: pendingOrder._id.toString(),
        courseId: targetCourse._id.toString(),
        studentId: String(targetStudentId),
        studentEmail: email || authUser?.email || '',
      },
      description: `ApkaGermanSchool Purchase - ${targetCourse.title}`,
      automatic_payment_methods: {
        enabled: true,
      },
    });

    // Save gatewayTransactionId to local order
    pendingOrder.gatewayTransactionId = paymentIntent.id;
    await pendingOrder.save();

    return NextResponse.json({
      success: true,
      clientSecret: paymentIntent.client_secret,
      paymentIntentId: paymentIntent.id,
      orderId: pendingOrder._id.toString(),
      publishableKey: config.publishableKey,
      amount: finalAmount,
      currency: 'EUR',
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Failed to create payment intent' },
      { status: 500 }
    );
  }
}
