export const DEFAULT_APP_VIEW_ORDER = [
  'overview',
  'workbench',
  'requests',
  'approval',
  'chat',
  'policies',
  'audit',
  'employees',
  'settings'
]

const ALWAYS_VISIBLE_VIEWS = new Set(['workbench', 'requests', 'chat', 'policies'])
const VIEW_ROLE_RULES = {
  overview: ['finance', 'executive'],
  approval: ['approver'],
  audit: ['auditor'],
  employees: ['manager'],
  settings: ['manager']
}

function normalizedRoleCodes(user) {
  if (!user) {
    return []
  }

  return Array.isArray(user.roleCodes) ? user.roleCodes.filter(Boolean) : []
}

export function isManagerUser(user) {
  return Boolean(user?.isAdmin) || normalizedRoleCodes(user).includes('manager')
}

export function canAccessAppView(user, viewId) {
  if (!viewId || !user) {
    return false
  }

  if (isManagerUser(user)) {
    return true
  }

  if (ALWAYS_VISIBLE_VIEWS.has(viewId)) {
    return true
  }

  const requiredRoles = VIEW_ROLE_RULES[viewId] || []
  const roleCodes = normalizedRoleCodes(user)
  return requiredRoles.some((roleCode) => roleCodes.includes(roleCode))
}

export function getAccessibleViewIds(user) {
  return DEFAULT_APP_VIEW_ORDER.filter((viewId) => canAccessAppView(user, viewId))
}

export function filterNavItemsByAccess(navItems, user) {
  return navItems.filter((item) => canAccessAppView(user, item.id))
}

export function resolveDefaultAuthorizedRoute(user) {
  const firstVisibleView = getAccessibleViewIds(user)[0]
  return { name: `app-${firstVisibleView || 'workbench'}` }
}
