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 { isValidEmail, 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, ['name', 'email', 'password']);
    if (!isValid) return errorResponse;

    const { name, email, password, phoneNumber = '' } = body;

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

    if (!isValidEmail(trimmedEmail)) {
      return NextResponse.json(
        { success: false, error: 'Please enter a valid email address' },
        { status: 400 }
      );
    }

    if (password.length < 6) {
      return NextResponse.json(
        { success: false, error: 'Password must be at least 6 characters long' },
        { status: 400 }
      );
    }

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

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

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

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