import { prisma } from "@/lib/prisma";
import type { InstitutionType } from "@prisma/client";

/** Short per-type prefixes for institution codes (e.g. SC-4821). */
const PREFIXES: Record<InstitutionType, string> = {
  PRIMARY_AND_HIGH_SCHOOL: "SC",
  COLLEGE_AND_UNIVERSITY: "CU",
  COACHING: "CA",
  MADRASHA: "MD",
};

/**
 * Generate a unique institution code: <TYPE-PREFIX>-<4 digits>.
 * Members (student/teacher/parent/staff) use this code at login to scope
 * their username to exactly one registered institution.
 */
export async function generateInstitutionCode(type: InstitutionType): Promise<string> {
  const prefix = PREFIXES[type] ?? "EM";
  for (let i = 0; i < 25; i++) {
    const code = `${prefix}-${1000 + Math.floor(Math.random() * 9000)}`;
    const exists = await prisma.institution.findUnique({ where: { code }, select: { id: true } });
    if (!exists) return code;
  }
  // Astronomically unlikely: fall back to a time-based suffix.
  return `${prefix}-${Date.now().toString(36).toUpperCase()}`;
}
