export const ROLES = {
  SUPER_ADMIN: 'super_admin',
  ADMIN: 'admin',
  MANAGER: 'manager',
  USER: 'user',
  ACCOUNTANT: 'accountant',
  SALES: 'sales',
  PURCHASES: 'purchases',
  INVENTORY: 'inventory',
  HR: 'hr',
  VIEWER: 'viewer',
} as const;

export type Role = (typeof ROLES)[keyof typeof ROLES];

export const ROLE_LABELS: Record<Role, string> = {
  [ROLES.SUPER_ADMIN]: 'Super Administrador',
  [ROLES.ADMIN]: 'Administrador',
  [ROLES.MANAGER]: 'Gerente',
  [ROLES.USER]: 'Usuario',
  [ROLES.ACCOUNTANT]: 'Contador',
  [ROLES.SALES]: 'Ventas',
  [ROLES.PURCHASES]: 'Compras',
  [ROLES.INVENTORY]: 'Inventario',
  [ROLES.HR]: 'Recursos Humanos',
  [ROLES.VIEWER]: 'Solo Lectura',
};

export const ROLE_HIERARCHY: Record<Role, number> = {
  [ROLES.SUPER_ADMIN]: 100,
  [ROLES.ADMIN]: 90,
  [ROLES.MANAGER]: 70,
  [ROLES.ACCOUNTANT]: 50,
  [ROLES.SALES]: 40,
  [ROLES.PURCHASES]: 40,
  [ROLES.INVENTORY]: 40,
  [ROLES.HR]: 40,
  [ROLES.USER]: 30,
  [ROLES.VIEWER]: 10,
};

export function hasRole(userRoles: string[], requiredRole: Role): boolean {
  return userRoles.some((role) => {
    const userLevel = ROLE_HIERARCHY[role as Role] ?? 0;
    const requiredLevel = ROLE_HIERARCHY[requiredRole];
    return userLevel >= requiredLevel;
  });
}

export function hasAnyRole(userRoles: string[], requiredRoles: Role[]): boolean {
  return requiredRoles.some((role) => hasRole(userRoles, role));
}
