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

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

function hasGlobalAccess(user: CurrentUser | null | undefined): boolean {
  return user?.app_role?.globalAccess === true;
}

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

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

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