/**
 * Pure RBAC helpers — foundation-auth-rbac. No DB access; operate on the
 * expanded claims already in the session JWT.
 *
 * Authorization in this system is permission-based: the session carries a flat
 * `permissions: string[]` (expanded from the member's role at token-issue
 * time). `hasPermission` is the canonical check. `isAtLeastRole` is a
 * convenience over the system-role hierarchy for the rare role-rank check.
 */
export type Permission = string

/** True when the expanded permission set contains `permission`. */
export function hasPermission(permissions: string[], permission: string): boolean {
  return permissions.includes(permission)
}

/**
 * System-role hierarchy, ascending. CONTRACTOR and VIEWER are both leaf roles
 * with no management rights; VIEWER ranks above CONTRACTOR (read-all vs
 * time-only). Custom (non-system) roles are not part of this ordering.
 */
const ROLE_ORDER = ['CONTRACTOR', 'VIEWER', 'MEMBER', 'ADMIN', 'OWNER'] as const

/**
 * True when `role` ranks at least as high as `minRole` in the system-role
 * hierarchy. Unknown / custom roles return false (not comparable).
 */
export function isAtLeastRole(role: string, minRole: string): boolean {
  const r = ROLE_ORDER.indexOf(role as (typeof ROLE_ORDER)[number])
  const m = ROLE_ORDER.indexOf(minRole as (typeof ROLE_ORDER)[number])
  if (r === -1 || m === -1) return false
  return r >= m
}
