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

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

// PATCH /api/students/[id]/status - Admin toggles student account status
export async function PATCH(req: NextRequest, { params }: Params) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

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

    if (!['active', 'deactivated'].includes(status)) {
      return NextResponse.json(
        { success: false, error: 'Status must be either "active" or "deactivated"' },
        { status: 400 }
      );
    }

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

    student.status = status;
    await student.save();

    return NextResponse.json({
      success: true,
      message: `Student account ${status === 'active' ? 'activated' : 'deactivated'} successfully`,
      student: {
        id: student._id,
        name: student.name,
        email: student.email,
        status: student.status,
      },
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error updating student status' },
      { status: 500 }
    );
  }
}
