const ADMIN_ROLES = new Set(["superadmin"]);

export function normalizeRole(role: string | null | undefined): string {
  return role?.trim().toLowerCase() ?? "";
}

export function normalizeRoles(
  roles: Array<string | null | undefined> | null | undefined,
): string[] {
  if (!roles?.length) {
    return [];
  }

  return Array.from(
    new Set(roles.map((role) => normalizeRole(role)).filter(Boolean)),
  );
}

export function hasRole(
  roles: Array<string | null | undefined> | null | undefined,
  expectedRole: string,
): boolean {
  return normalizeRoles(roles).includes(normalizeRole(expectedRole));
}

export function isAdminRole(
  roles: Array<string | null | undefined> | null | undefined,
): boolean {
  return normalizeRoles(roles).some((role) => ADMIN_ROLES.has(role));
}

export function formatRoleLabel(role: string | null | undefined): string {
  const normalizedRole = normalizeRole(role);

  switch (normalizedRole) {
    case "superadmin":
      return "Superadmin";
    case "user":
      return "User";
    default:
      return role?.trim() || "User";
  }
}
