import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { Student } from '@/models/Student';
import { requireAdmin } from '@/lib/auth';

// GET /api/students - Admin lists students with search & filter
export async function GET(req: NextRequest) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const { searchParams } = new URL(req.url);
    const search = searchParams.get('search') || '';
    const status = searchParams.get('status');
    const page = parseInt(searchParams.get('page') || '1', 10);
    const limit = parseInt(searchParams.get('limit') || '20', 10);
    const skip = (page - 1) * limit;

    const query: Record<string, any> = {};
    if (status && status !== 'all') {
      query.status = status;
    }
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { email: { $regex: search, $options: 'i' } },
        { phoneNumber: { $regex: search, $options: 'i' } },
      ];
    }

    const total = await Student.countDocuments(query);
    const students = await Student.find(query)
      .select('-password')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit);

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

// POST /api/students - Admin registers a new student
export async function POST(req: NextRequest) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const body = await req.json();
    const { name, email, password, phoneNumber, status } = body;

    if (!name || !name.trim()) {
      return NextResponse.json(
        { success: false, error: 'Student name is required' },
        { status: 400 }
      );
    }

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

    const trimmedEmail = email.trim().toLowerCase();

    // Check if student with email already exists
    const existingStudent = await Student.findOne({ email: trimmedEmail });
    if (existingStudent) {
      return NextResponse.json(
        { success: false, error: 'A student account with this email already exists' },
        { status: 400 }
      );
    }

    const defaultPassword = password && password.trim() ? password.trim() : 'Student@123456';

    const newStudent = await Student.create({
      name: name.trim(),
      email: trimmedEmail,
      password: defaultPassword,
      phoneNumber: phoneNumber ? phoneNumber.trim() : '',
      status: status === 'deactivated' ? 'deactivated' : 'active',
    });

    const studentObj = newStudent.toObject();
    delete studentObj.password;

    return NextResponse.json(
      {
        success: true,
        message: 'Student registered successfully',
        student: studentObj,
      },
      { status: 201 }
    );
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error registering student' },
      { status: 500 }
    );
  }
}

