import { prisma } from "@/lib/prisma";

/* Shared helpers for the Student Identity feature (/portal/identity):
   roll / registration / ID-card data maintained by the institution admin
   or by admin-assigned staff maintainers (optionally scoped to classes). */

/** A manager's scope Json → class-id list; null/empty array means all classes. */
export function parseScope(scopeClassItemIds: unknown): number[] | null {
  if (!Array.isArray(scopeClassItemIds)) return null;
  const ids = scopeClassItemIds.map(Number).filter((n) => Boolean(n));
  return ids.length ? ids : null;
}

/** The IdentityManager record behind a member session's staff login, if any. */
export async function getManagerForUser(userId: number, institutionId: number) {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { staffId: true },
  });
  if (!user?.staffId) return null;
  return prisma.identityManager.findFirst({
    where: { institutionId, staffId: user.staffId },
    include: {
      staff: { select: { id: true, name: true, employeeCode: true, designation: true } },
    },
  });
}

/** Whether a class-scoped list permits the given class. null scope = all. */
export function scopeAllows(scope: number[] | null, classItemId: number | null): boolean {
  if (scope == null) return true;
  return classItemId != null && scope.includes(classItemId);
}
