export const AI_SIDEBAR_BASE_BUSINESS_VIEW_IDS = ['documents', 'receiptFolder', 'policies']

const ROLE_VIEW_ADDITIONS = {
  budget: ['budget'],
  finance: ['overview', 'audit', 'digitalEmployees'],
  manager: ['overview', 'employees'],
  executive: ['budget', 'overview'],
  admin: ['budget', 'overview', 'audit', 'digitalEmployees', 'employees']
}

function normalizeRoleCode(value) {
  const normalized = String(value || '').trim().toLowerCase()
  return normalized === 'auditor' ? 'budget_monitor' : normalized
}

function normalizedRoleCodes(user = {}) {
  return Array.isArray(user.roleCodes)
    ? user.roleCodes.map((item) => normalizeRoleCode(item)).filter(Boolean)
    : []
}

function normalizeProfileText(user = {}) {
  return [
    user.role,
    user.position,
    user.department,
    user.departmentName,
    user.department_name,
    user.grade
  ]
    .map((item) => String(item || '').trim().toLowerCase())
    .filter(Boolean)
    .join(' ')
}

function isPlatformAdminProfile(user = {}, roleCodes = []) {
  const username = String(user.username || user.account || '').trim().toLowerCase()
  const role = String(user.role || '').trim().toLowerCase()

  return (
    Boolean(user.isAdmin)
    || username === 'admin'
    || role === 'admin'
    || role === '管理员'
    || role === '系统管理员'
    || roleCodes.includes('admin')
  )
}

function addViewIds(target, ids = []) {
  ids.forEach((id) => target.add(id))
}

export function resolveAiSidebarBusinessViewIds(user = {}) {
  const roleCodes = normalizedRoleCodes(user)
  const roleCodeSet = new Set(roleCodes)
  const profileText = normalizeProfileText(user)
  const viewIds = new Set(AI_SIDEBAR_BASE_BUSINESS_VIEW_IDS)

  if (isPlatformAdminProfile(user, roleCodes)) {
    addViewIds(viewIds, ROLE_VIEW_ADDITIONS.admin)
  }

  if (roleCodeSet.has('budget_monitor') || profileText.includes('预算')) {
    addViewIds(viewIds, ROLE_VIEW_ADDITIONS.budget)
  }

  if (roleCodeSet.has('finance') || profileText.includes('财务')) {
    addViewIds(viewIds, ROLE_VIEW_ADDITIONS.finance)
  }

  if (roleCodeSet.has('manager') || profileText.includes('经理') || profileText.includes('主管')) {
    addViewIds(viewIds, ROLE_VIEW_ADDITIONS.manager)
  }

  if (roleCodeSet.has('executive') || profileText.includes('高管') || profileText.includes('总监')) {
    addViewIds(viewIds, ROLE_VIEW_ADDITIONS.executive)
  }

  return Array.from(viewIds)
}
