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

interface Params {
  params: { id: string };
}

// GET /api/students/[id]
export async function GET(req: NextRequest, { params }: Params) {
  const auth = requireAuth(req);
  if (auth instanceof NextResponse) return auth;

  // Only admin or the student themselves can view the profile
  if (auth.user.role === 'student' && auth.user.id !== params.id) {
    return NextResponse.json({ success: false, error: 'Forbidden' }, { status: 403 });
  }

  try {
    await dbConnect();
    const student = await Student.findById(params.id).select('-password');
    if (!student) {
      return NextResponse.json({ success: false, error: 'Student not found' }, { status: 404 });
    }

    return NextResponse.json({ success: true, student });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error fetching student' },
      { status: 500 }
    );
  }
}

// PUT /api/students/[id]
export async function PUT(req: NextRequest, { params }: Params) {
  const auth = requireAuth(req);
  if (auth instanceof NextResponse) return auth;

  if (auth.user.role === 'student' && auth.user.id !== params.id) {
    return NextResponse.json({ success: false, error: 'Forbidden' }, { status: 403 });
  }

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

    const student = await Student.findById(params.id);
    if (!student) {
      return NextResponse.json({ success: false, error: 'Student not found' }, { status: 404 });
    }

    if (name !== undefined) {
      if (typeof name !== 'string' || name.trim() === '') {
        return NextResponse.json(
          { success: false, error: 'Student name cannot be empty' },
          { status: 400 }
        );
      }
      student.name = name.trim();
    }

    if (email !== undefined && email.trim().toLowerCase() !== student.email) {
      const trimmedEmail = email.trim().toLowerCase();
      if (!isValidEmail(trimmedEmail)) {
        return NextResponse.json(
          { success: false, error: 'Please enter a valid email address' },
          { status: 400 }
        );
      }
      const existing = await Student.findOne({ email: trimmedEmail });
      if (existing) {
        return NextResponse.json(
          { success: false, error: 'A student with this email address already exists' },
          { status: 409 }
        );
      }
      student.email = trimmedEmail;
    }

    if (phoneNumber !== undefined) student.phoneNumber = String(phoneNumber).trim();

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

    await student.save();

    return NextResponse.json({
      success: true,
      message: 'Student profile updated successfully',
      student: {
        id: student._id,
        _id: student._id,
        name: student.name,
        email: student.email,
        phoneNumber: student.phoneNumber,
        status: student.status,
      },
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error updating student' },
      { status: 500 }
    );
  }
}
