import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { Student } from '@/models/Student';
import { signToken } from '@/lib/auth';
import { rateLimiter } from '@/lib/rateLimiter';
import { validateFields } from '@/lib/validation';

export async function POST(req: NextRequest) {
  const rateLimitRes = rateLimiter(req, 10, 15 * 60 * 1000);
  if (rateLimitRes) return rateLimitRes;

  try {
    await dbConnect();
    const body = await req.json();

    const { isValid, errorResponse } = validateFields(body, ['email', 'password']);
    if (!isValid) return errorResponse;

    const { email, password } = body;

    const student = await Student.findOne({ email: email.toLowerCase() }).select('+password');
    if (!student) {
      return NextResponse.json(
        { success: false, error: 'Invalid email or password' },
        { status: 401 }
      );
    }

    if (student.status === 'deactivated') {
      return NextResponse.json(
        {
          success: false,
          error: 'Your account has been deactivated. Please contact support.',
        },
        { status: 403 }
      );
    }

    const isMatch = await student.comparePassword(password);
    if (!isMatch) {
      return NextResponse.json(
        { success: false, error: 'Invalid email or password' },
        { status: 401 }
      );
    }

    student.lastLogin = new Date();
    await student.save();

    const token = signToken({
      id: student._id.toString(),
      email: student.email,
      role: 'student',
      status: student.status,
    });

    return NextResponse.json({
      success: true,
      message: 'Student login successful',
      student: {
        id: student._id,
        name: student.name,
        email: student.email,
        phoneNumber: student.phoneNumber,
        status: student.status,
        lastLogin: student.lastLogin,
      },
      token,
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error during student login' },
      { status: 500 }
    );
  }
}
