import type { AuthPermission, AuthRole, AuthUser } from '@/modules/auth/types/auth.types'

const DEVELOPER_ROLE = 'DEVELOPER'

export function getActiveRolePermissions(
  user: AuthUser | null | undefined,
  activeRole: AuthRole | null | undefined,
): AuthPermission[] {
  if (!user?.roles?.length || !activeRole) {
    return []
  }

  return user.roles.find((role) => role.id === activeRole.id)?.permissions ?? []
}

export function hasActiveRolePermission(
  user: AuthUser | null | undefined,
  activeRole: AuthRole | null | undefined,
  permission: string,
): boolean {
  if (activeRole?.name === DEVELOPER_ROLE) {
    return true
  }

  return getActiveRolePermissions(user, activeRole).some(
    (item) => item.name === permission,
  )
}

export function hasAnyActiveRolePermission(
  user: AuthUser | null | undefined,
  activeRole: AuthRole | null | undefined,
  permissions: string[],
): boolean {
  return permissions.some((permission) =>
    hasActiveRolePermission(user, activeRole, permission),
  )
}
