import type { Prisma, PrismaClient } from "@prisma/client";

export type TrainingRosterCounts = { active: number; reserve: number; total: number };

/** Aggregate trainee roster counts per training without loading every trainee row. */
export async function traineeCountsByTrainingId(
  prisma: PrismaClient,
  args: {
    projectId: bigint;
    trainingProviderId?: bigint;
    trainingIds?: bigint[];
  },
): Promise<Map<string, TrainingRosterCounts>> {
  const where: Prisma.TraineeWhereInput = {
    projectId: args.projectId,
    trainingId: { not: null },
    ...(args.trainingProviderId ? { trainingProviderId: args.trainingProviderId } : {}),
    ...(args.trainingIds?.length ? { trainingId: { in: args.trainingIds } } : {}),
  };
  const rows = await prisma.trainee.groupBy({
    by: ["trainingId", "rosterRole"],
    where,
    _count: { _all: true },
  });
  const map = new Map<string, TrainingRosterCounts>();
  for (const r of rows) {
    if (!r.trainingId) continue;
    const key = r.trainingId.toString();
    const cur = map.get(key) ?? { active: 0, reserve: 0, total: 0 };
    const c = r._count._all;
    if (r.rosterRole === "active") cur.active += c;
    else if (r.rosterRole === "reserve") cur.reserve += c;
    cur.total += c;
    map.set(key, cur);
  }
  return map;
}
