/**
 * Role normalization utilities (pure functions).
 *
 * These helpers map various role names to the canonical K12 role set.
 * `grade_head` and `teaching_head` are preserved as distinct roles (they
 * carry different data-scope semantics from `teacher`).
 */

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

/**
 * Normalize a single role value to one of the canonical roles.
 * Unknown values fall back to `student`.
 */
export const normalizeRole = (value: unknown): NormalizedRole => {
  const role = String(value ?? "").trim().toLowerCase()
  if (
    role === "admin" ||
    role === "grade_head" ||
    role === "teaching_head" ||
    role === "teacher" ||
    role === "student" ||
    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 > grade_head > teaching_head > teacher > student > parent.
 */
export const resolvePrimaryRole = (roleNames: string[]): NormalizedRole => {
  const mapped = roleNames.map((name) => normalizeRole(name)).filter(Boolean)
  if (mapped.includes("admin")) return "admin"
  if (mapped.includes("grade_head")) return "grade_head"
  if (mapped.includes("teaching_head")) return "teaching_head"
  if (mapped.includes("teacher")) return "teacher"
  if (mapped.includes("student")) return "student"
  if (mapped.includes("parent")) return "parent"
  return "student"
}
