import { NextResponse, type NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { getSessionUser } from "@/lib/auth/session";
import { canManageOwnedResource } from "@/lib/auth/rbac";

/**
 * Students eligible to join a class.
 *
 * Returns only ACTIVE students not already enrolled, and only to staff who own
 * the class. Used by the roster dialog so the whole student body is never
 * shipped to the browser up front.
 */
export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ classId: string }> }
) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Tidak terautentikasi." }, { status: 401 });
  }
  if (user.role === "STUDENT") {
    return NextResponse.json({ error: "Tidak diizinkan." }, { status: 403 });
  }

  const { classId } = await params;

  const classroom = await prisma.classroom.findUnique({
    where: { id: classId },
    select: { teacherId: true },
  });
  if (!classroom) {
    return NextResponse.json({ error: "Kelas tidak ditemukan." }, { status: 404 });
  }
  if (!canManageOwnedResource(user, classroom.teacherId)) {
    return NextResponse.json({ error: "Tidak diizinkan." }, { status: 403 });
  }

  const students = await prisma.user.findMany({
    where: {
      role: "STUDENT",
      status: "ACTIVE",
      enrollments: { none: { classId } },
    },
    orderBy: { fullName: "asc" },
    take: 500,
    select: { id: true, fullName: true, username: true, gradeLevel: true },
  });

  return NextResponse.json(students, {
    headers: { "Cache-Control": "private, no-store" },
  });
}
