import type { CurrentUser } from '@/shared/types/auth';
import {
  GLOBAL_BYPASS_EXCLUDED_PERMISSIONS,
  type PermissionName,
} from '@/shared/auth/permissions';

function permissionsOf(user: CurrentUser | null | undefined): readonly string[] {
  return user?.permissions ?? [];
}

function hasPermissionBypass(user: CurrentUser | null | undefined): boolean {
  return user?.app_role?.name === 'super_admin';
}

function allowsGlobalBypass(permission: PermissionName): boolean {
  return !GLOBAL_BYPASS_EXCLUDED_PERMISSIONS.some((name) => name === permission);
}

export function hasPermission(
  user: CurrentUser | null | undefined,
  permission: PermissionName,
): boolean {
  return (hasPermissionBypass(user) && allowsGlobalBypass(permission))
    || permissionsOf(user).includes(permission);
}

export function hasAnyPermission(
  user: CurrentUser | null | undefined,
  permissions: readonly PermissionName[],
): boolean {
  const granted = permissionsOf(user);
  return permissions.some((permission) =>
    (hasPermissionBypass(user) && allowsGlobalBypass(permission)) || granted.includes(permission),
  );
}

export function hasAllPermissions(
  user: CurrentUser | null | undefined,
  permissions: readonly PermissionName[],
): boolean {
  const granted = permissionsOf(user);
  return permissions.every((permission) =>
    (hasPermissionBypass(user) && allowsGlobalBypass(permission)) || granted.includes(permission),
  );
}
