/**
 * Authorization scope of a role (Workstream 3 §3.1). Determines the breadth of
 * a role's reach: platform-wide, a single organization, a single campus, the
 * external-user surface, or the unauthenticated guest. Stored on `roles.scope`.
 */
export const ROLE_SCOPES = Object.freeze({
  SYSTEM: 'system',
  ORGANIZATION: 'organization',
  CAMPUS: 'campus',
  EXTERNAL: 'external',
  GUEST: 'guest',
});

export type RoleScope = (typeof ROLE_SCOPES)[keyof typeof ROLE_SCOPES];

export const ROLE_SCOPE_VALUES: readonly RoleScope[] = Object.freeze(
  Object.values(ROLE_SCOPES),
);

/**
 * The 11 first-class platform roles (Workstream 3 §3.1). The stored `roles.name`
 * uses these stable machine values; `roles.scope` is the matching scope. `guest`
 * is the unauthenticated fallback (the seeded `Public` row), not an assignable
 * user role. `globalAccess` (system roles only) bypasses tenant filtering.
 */
export const ROLE_NAMES = Object.freeze({
  SUPER_ADMIN: 'super_admin',
  SYSTEM_ADMIN: 'system_admin',
  OWNER: 'owner',
  SUPERINTENDENT: 'superintendent',
  DIRECTOR: 'director',
  OFFICE_MANAGER: 'office_manager',
  TEACHER: 'teacher',
  SUPPORT_STAFF: 'support_staff',
  STUDENT: 'student',
  GUARDIAN: 'guardian',
  GUEST: 'guest',
});

export type RoleName = (typeof ROLE_NAMES)[keyof typeof ROLE_NAMES];

export interface RoleDefinition {
  readonly name: RoleName;
  readonly scope: RoleScope;
  /** Bypasses tenant/organization filtering. System roles only. */
  readonly globalAccess: boolean;
}

export const ROLE_DEFINITIONS: readonly RoleDefinition[] = Object.freeze([
  { name: ROLE_NAMES.SUPER_ADMIN, scope: ROLE_SCOPES.SYSTEM, globalAccess: true },
  { name: ROLE_NAMES.SYSTEM_ADMIN, scope: ROLE_SCOPES.SYSTEM, globalAccess: true },
  { name: ROLE_NAMES.OWNER, scope: ROLE_SCOPES.ORGANIZATION, globalAccess: false },
  { name: ROLE_NAMES.SUPERINTENDENT, scope: ROLE_SCOPES.ORGANIZATION, globalAccess: false },
  { name: ROLE_NAMES.DIRECTOR, scope: ROLE_SCOPES.CAMPUS, globalAccess: false },
  { name: ROLE_NAMES.OFFICE_MANAGER, scope: ROLE_SCOPES.CAMPUS, globalAccess: false },
  { name: ROLE_NAMES.TEACHER, scope: ROLE_SCOPES.CAMPUS, globalAccess: false },
  { name: ROLE_NAMES.SUPPORT_STAFF, scope: ROLE_SCOPES.CAMPUS, globalAccess: false },
  { name: ROLE_NAMES.STUDENT, scope: ROLE_SCOPES.EXTERNAL, globalAccess: false },
  { name: ROLE_NAMES.GUARDIAN, scope: ROLE_SCOPES.EXTERNAL, globalAccess: false },
  { name: ROLE_NAMES.GUEST, scope: ROLE_SCOPES.GUEST, globalAccess: false },
]);

export const ROLE_NAME_VALUES: readonly RoleName[] = Object.freeze(
  ROLE_DEFINITIONS.map((role) => role.name),
);

/** Staff HR type → the campus role assigned to that staff member. */
export const STAFF_TYPE_TO_ROLE_NAME: Record<string, RoleName> = Object.freeze({
  teacher: ROLE_NAMES.TEACHER,
  admin: ROLE_NAMES.OFFICE_MANAGER,
  support: ROLE_NAMES.SUPPORT_STAFF,
});
