import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";

/** Students of a paper's exam class — the print view prints one OMR sheet
 *  per student. */
export async function GET(req: Request) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const scheduleId = Number(new URL(req.url).searchParams.get("examScheduleId"));
  const schedule = await prisma.examSchedule.findFirst({
    where: { id: scheduleId, exam: { institutionId: session.institutionId } },
    select: { exam: { select: { classItemId: true, name: true, nameBn: true } }, subjectItem: { select: { name: true, nameBn: true } } },
  });
  if (!schedule) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const students = await prisma.student.findMany({
    where: { institutionId: session.institutionId, status: "ACTIVE", classItemId: schedule.exam.classItemId },
    select: { roll: true, name: true },
    orderBy: { roll: "asc" },
  });
  return NextResponse.json({
    examName: schedule.exam.name,
    examNameBn: schedule.exam.nameBn,
    subject: schedule.subjectItem?.name ?? "",
    subjectBn: schedule.subjectItem?.nameBn ?? null,
    students,
  });
}
