import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { CoursePurchaseHistory } from '@/models/CoursePurchaseHistory';
import { Student } from '@/models/Student';
import { Order } from '@/models/Order';
import { Course } from '@/models/Course';
import { Lesson } from '@/models/Lesson';
import { requireAuth } from '@/lib/auth';

// GET /api/purchase-history - List purchase history records
export async function GET(req: NextRequest) {
  const auth = requireAuth(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const { searchParams } = new URL(req.url);
    const isAdmin = auth.user.role === 'admin' || auth.user.role === 'super_admin';

    const query: Record<string, any> = {};

    if (!isAdmin) {
      query.student = auth.user.id;
    } else {
      const studentId = searchParams.get('student');
      const paymentMethod = searchParams.get('paymentMethod');
      const status = searchParams.get('status');

      if (studentId) query.student = studentId;
      if (paymentMethod) query.paymentMethod = paymentMethod;
      if (status) query.paymentStatus = status;
    }

    const page = parseInt(searchParams.get('page') || '1', 10);
    const limit = parseInt(searchParams.get('limit') || '20', 10);
    const skip = (page - 1) * limit;

    const total = await CoursePurchaseHistory.countDocuments(query);
    const history = await CoursePurchaseHistory.find(query)
      .populate('student', 'name email phoneNumber')
      .populate('order', 'gateway status initiatedAt confirmedAt')
      .populate('courseId', 'title level courseType regularPrice offerPrice')
      .populate('lessons', 'title price chapterNumber durationMinutes')
      .sort({ purchasedAt: -1 })
      .skip(skip)
      .limit(limit);

    return NextResponse.json({
      success: true,
      total,
      page,
      pages: Math.ceil(total / limit),
      count: history.length,
      history,
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error fetching purchase history' },
      { status: 500 }
    );
  }
}
