import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAnyRole } from "@/lib/auth";
import { STAFF_SIDE_ROLES } from "@/lib/auth";
import { getManagerForUser, parseScope } from "@/lib/identity";

/* Student Identity page data. Admins see every student of the institution
   plus the maintainer-assignment panel data; TEACHER/STAFF members see only
   what their admin-assigned manager scope allows (no assignment → empty). */
export async function GET() {
  const session = await requireAnyRole(["INSTITUTION_ADMIN", ...STAFF_SIDE_ROLES]);
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const institutionId = session.institutionId;

  // member roles must hold an IdentityManager assignment
  let scope: number[] | null = null;
  if (session.role !== "INSTITUTION_ADMIN") {
    const manager = await getManagerForUser(session.userId, institutionId);
    if (!manager) {
      return NextResponse.json({ access: "NONE", students: [], classes: [] });
    }
    scope = parseScope(manager.scopeClassItemIds);
  }

  const classes = await prisma.academicSelection.findMany({
    where: {
      institutionId,
      academicItem: { category: "CLASS" },
      ...(scope ? { academicItemId: { in: scope } } : {}),
    },
    select: { academicItemId: true, academicItem: { select: { name: true, nameBn: true } } },
    orderBy: { academicItem: { name: "asc" } },
  });
  const classOptions = classes.map((c) => ({
    id: c.academicItemId,
    name: c.academicItem.name,
    nameBn: c.academicItem.nameBn,
  }));

  const students = await prisma.student.findMany({
    where: {
      institutionId,
      ...(scope ? { classItemId: { in: scope } } : {}),
    },
    orderBy: [{ classItemId: "asc" }, { roll: "asc" }],
    select: {
      id: true,
      roll: true,
      registrationNo: true,
      cardNo: true,
      rfidCardNo: true,
      cardIssuedAt: true,
      cardValidTill: true,
      bloodGroup: true,
      name: true,
      classItemId: true,
      classItem: { select: { name: true, nameBn: true } },
      sectionItem: { select: { name: true, nameBn: true } },
    },
  });

  if (session.role !== "INSTITUTION_ADMIN") {
    return NextResponse.json({ access: "MANAGER", students, classes: classOptions });
  }

  // Admin-only: current assignments + assignable staff for the panel
  const [managers, staff] = await Promise.all([
    prisma.identityManager.findMany({
      where: { institutionId },
      orderBy: { createdAt: "desc" },
      include: { staff: { select: { id: true, name: true, employeeCode: true, designation: true } } },
    }),
    prisma.staff.findMany({
      where: { institutionId, status: "ACTIVE" },
      orderBy: { name: "asc" },
      select: { id: true, name: true, employeeCode: true, designation: true },
    }),
  ]);
  const assignedStaffIds = new Set(managers.map((m) => m.staffId));

  return NextResponse.json({
    access: "ADMIN",
    students,
    classes: classOptions,
    managers: managers.map((m) => ({
      staffId: m.staffId,
      staffName: m.staff.name,
      employeeCode: m.staff.employeeCode,
      designation: m.staff.designation,
      scope: parseScope(m.scopeClassItemIds),
      createdAt: m.createdAt,
    })),
    staffOptions: staff.map((s) => ({ ...s, isManager: assignedStaffIds.has(s.id) })),
  });
}
