/**
 * Role normalization utilities (pure functions).
 *
 * These helpers map various role names (including legacy aliases) to the
 * canonical K12 role set: admin / teacher / student / parent.
 */

export type NormalizedRole = "admin" | "teacher" | "student" | "parent"

/**
 * Normalize a single role value to one of the canonical roles.
 * Legacy aliases such as `grade_head` / `teaching_head` collapse to `teacher`.
 * Unknown values fall back to `student`.
 */
export const normalizeRole = (value: unknown): NormalizedRole => {
  const role = String(value ?? "").trim().toLowerCase()
  if (role === "grade_head" || role === "teaching_head") return "teacher"
  if (role === "admin" || role === "student" || role === "teacher" || role === "parent") return role
  return "student"
}

/**
 * Given a list of role names (e.g. from `users_to_roles`), resolve the
 * primary role used for routing/permission checks. Priority order:
 * admin > teacher > parent > student.
 */
export const resolvePrimaryRole = (roleNames: string[]): NormalizedRole => {
  const mapped = roleNames.map((name) => normalizeRole(name)).filter(Boolean)
  if (mapped.includes("admin")) return "admin"
  if (mapped.includes("teacher")) return "teacher"
  if (mapped.includes("parent")) return "parent"
  if (mapped.includes("student")) return "student"
  return "student"
}
