import assert from 'node:assert/strict'
import test from 'node:test'

import {
  canApproveBudgetExpenseApplications,
  canApproveLeaderExpenseClaims,
  canAccessAppView,
  canDeleteArchivedExpenseClaims,
  canEditBudgetCenter,
  filterNavItemsByAccess,
  getAccessibleViewIds,
  isCurrentDirectManagerForRequest,
  isCurrentRequestApplicant,
  canManageExpenseClaims,
  canReturnExpenseClaims,
  resolveDefaultAuthorizedRoute,
  canSwitchBudgetDepartments
} from '../src/utils/accessControl.js'
import { canProcessApprovalRequest } from '../src/utils/approvalInbox.js'

test('direct approvers can return claims without receiving delete permissions', () => {
  const managerUser = { roleCodes: ['manager'] }
  const approverUser = { roleCodes: ['approver'] }

  assert.equal(canReturnExpenseClaims(managerUser), true)
  assert.equal(canReturnExpenseClaims(approverUser), true)
  assert.equal(canApproveLeaderExpenseClaims(managerUser), true)
  assert.equal(canApproveLeaderExpenseClaims(approverUser), true)
  assert.equal(canApproveBudgetExpenseApplications({ roleCodes: ['budget_monitor'], grade: 'P6' }), false)
  assert.equal(canApproveBudgetExpenseApplications({ roleCodes: ['budget_monitor'], grade: 'P8' }), true)
  assert.equal(
    canApproveBudgetExpenseApplications(
      { roleCodes: ['budget_monitor'], grade: 'P8', departmentName: '交付部' },
      { departmentName: '交付部' }
    ),
    true
  )
  assert.equal(
    canApproveBudgetExpenseApplications(
      { roleCodes: ['budget_monitor'], grade: 'P8', departmentName: '财务部' },
      { departmentName: '交付部' }
    ),
    false
  )
  assert.equal(canApproveBudgetExpenseApplications({ roleCodes: [], grade: 'P8' }), false)
  assert.equal(canApproveBudgetExpenseApplications({ roleCodes: ['executive'] }), false)
  assert.equal(canApproveBudgetExpenseApplications({ roleCodes: ['executive'], grade: 'P7' }), false)
  assert.equal(canApproveBudgetExpenseApplications({ roleCodes: ['executive'], grade: 'P8' }), true)
  assert.equal(canManageExpenseClaims(managerUser), false)
  assert.equal(canManageExpenseClaims(approverUser), false)
})

test('finance can return and final approve, executives can manage claim visibility only', () => {
  assert.equal(canReturnExpenseClaims({ roleCodes: ['finance'] }), true)
  assert.equal(canApproveLeaderExpenseClaims({ roleCodes: ['finance'] }), false)
  assert.equal(canManageExpenseClaims({ roleCodes: ['finance'] }), false)
  assert.equal(canReturnExpenseClaims({ roleCodes: ['executive'] }), true)
  assert.equal(canManageExpenseClaims({ roleCodes: ['executive'] }), true)
})

test('archived claims can only be deleted by admin users', () => {
  assert.equal(canDeleteArchivedExpenseClaims({ roleCodes: ['executive'] }), false)
  assert.equal(canDeleteArchivedExpenseClaims({ roleCodes: ['finance'] }), false)
  assert.equal(canDeleteArchivedExpenseClaims({ isAdmin: true, roleCodes: ['manager'] }), true)
  assert.equal(canDeleteArchivedExpenseClaims({ username: 'superadmin', roleCodes: ['manager'] }), true)
})

test('legacy reimbursement approval and archive centers are no longer accessible app views', () => {
  const adminUser = { isAdmin: true, roleCodes: ['manager', 'finance'] }

  assert.equal(canAccessAppView(adminUser, 'requests'), false)
  assert.equal(canAccessAppView(adminUser, 'approval'), false)
  assert.equal(canAccessAppView(adminUser, 'archive'), false)
  assert.equal(canAccessAppView(adminUser, 'logs'), false)
  assert.equal(canAccessAppView(adminUser, 'documents'), true)
})

test('platform admin users do not enter the personal workbench', () => {
  const adminUser = { username: 'admin', isAdmin: true, roleCodes: ['manager', 'finance'] }
  const legacyAdminUser = { username: 'superadmin', roleCodes: ['manager'] }
  const employeeUser = { username: 'employee@example.com', roleCodes: [] }
  const navItems = [
    { id: 'workbench', label: '个人工作台' },
    { id: 'documents', label: '单据中心' },
    { id: 'overview', label: '分析看板' },
    { id: 'settings', label: '系统设置' }
  ]

  assert.equal(canAccessAppView(adminUser, 'workbench'), false)
  assert.equal(canAccessAppView(legacyAdminUser, 'workbench'), false)
  assert.equal(canAccessAppView(employeeUser, 'workbench'), true)
  assert.equal(getAccessibleViewIds(adminUser).includes('workbench'), false)
  assert.deepEqual(resolveDefaultAuthorizedRoute(legacyAdminUser), { name: 'app-documents' })
  assert.deepEqual(resolveDefaultAuthorizedRoute(adminUser), { name: 'app-documents' })
  assert.deepEqual(
    filterNavItemsByAccess(navItems, adminUser).map((item) => item.id),
    ['documents', 'overview', 'settings']
  )
})

test('budget center is visible to platform admin, budget monitor, and executive roles only', () => {
  assert.equal(canAccessAppView({ isAdmin: true, roleCodes: ['manager'] }, 'budget'), true)
  assert.equal(canAccessAppView({ username: 'admin', roleCodes: ['manager'] }, 'budget'), true)
  assert.equal(canAccessAppView({ roleCodes: ['budget_monitor'] }, 'budget'), true)
  assert.equal(canAccessAppView({ roleCodes: ['auditor'] }, 'budget'), true)
  assert.equal(canAccessAppView({ roleCodes: ['executive'] }, 'budget'), true)
  assert.equal(canAccessAppView({ roleCodes: ['finance'] }, 'budget'), false)
  assert.equal(canAccessAppView({ roleCodes: ['manager'] }, 'budget'), false)
})

test('system settings are visible to platform admin instead of business managers', () => {
  assert.equal(canAccessAppView({ isAdmin: true, roleCodes: ['manager'] }, 'settings'), true)
  assert.equal(canAccessAppView({ roleCodes: ['manager'] }, 'settings'), false)
})

test('budget edit and department switching are limited to admin and senior finance', () => {
  assert.equal(canEditBudgetCenter({ username: 'admin', roleCodes: ['manager'] }), true)
  assert.equal(canSwitchBudgetDepartments({ username: 'admin', roleCodes: ['manager'] }), true)
  assert.equal(canEditBudgetCenter({ roleCodes: ['executive'] }), true)
  assert.equal(canSwitchBudgetDepartments({ roleCodes: ['executive'] }), true)
  assert.equal(canEditBudgetCenter({ roleCodes: ['budget_monitor'] }), false)
  assert.equal(canSwitchBudgetDepartments({ roleCodes: ['budget_monitor'] }), false)
})

test('finance approval inbox only processes finance-stage requests', () => {
  const financeUser = { roleCodes: ['finance'], name: '财务' }

  assert.equal(
    canProcessApprovalRequest({ workflowNode: '财务审批', person: '张三' }, financeUser),
    true
  )
  assert.equal(
    canProcessApprovalRequest({ workflowNode: '直属领导审批', person: '张三' }, financeUser),
    false
  )
})

test('budget approval inbox only processes budget-stage requests for department P8 budget approvers', () => {
  const budgetUser = { roleCodes: ['budget_monitor'], grade: 'P8', name: '赵预算', departmentName: '交付部' }
  const otherDepartmentBudgetUser = { roleCodes: ['budget_monitor'], grade: 'P8', name: '王预算', departmentName: '财务部' }
  const seniorFinanceUser = { roleCodes: ['executive'], grade: 'P7', name: '高级财务' }
  const p8ExecutiveBudgetUser = { roleCodes: ['executive'], grade: 'P8', name: 'P8 Executive', departmentName: '交付部' }
  const p8WithoutBudgetRole = { roleCodes: ['manager'], grade: 'P8', name: '高职级经理' }

  assert.equal(
    canProcessApprovalRequest({ workflowNode: '预算管理者审批', person: '张三', departmentName: '交付部' }, budgetUser),
    true
  )
  assert.equal(
    canProcessApprovalRequest({ workflowNode: '预算管理者审批', person: '张三', departmentName: '交付部' }, seniorFinanceUser),
    false
  )
  assert.equal(
    canProcessApprovalRequest({ workflowNode: '预算管理者审批', person: '张三', departmentName: '交付部' }, p8ExecutiveBudgetUser),
    true
  )
  assert.equal(
    canProcessApprovalRequest(
      { workflowNode: '预算管理者审批', person: '张三', departmentName: '交付部' },
      otherDepartmentBudgetUser
    ),
    false
  )
  assert.equal(
    canProcessApprovalRequest({ workflowNode: '预算管理者审批', person: '张三' }, p8WithoutBudgetRole),
    false
  )
  assert.equal(
    canProcessApprovalRequest({ workflowNode: '财务审批', person: '张三' }, budgetUser),
    false
  )
})

test('users with both finance and manager roles can process both relevant stages', () => {
  const financeManagerUser = { roleCodes: ['finance', 'manager'], name: '李经理' }

  assert.equal(
    canProcessApprovalRequest({ workflowNode: '财务审批', person: '张三' }, financeManagerUser),
    true
  )
  assert.equal(
    canProcessApprovalRequest(
      { workflowNode: '直属领导审批', person: '张三', managerName: '李经理' },
      financeManagerUser
    ),
    true
  )
  assert.equal(
    canProcessApprovalRequest(
      { workflowNode: '直属领导审批', person: '李经理', managerName: '王总' },
      financeManagerUser
    ),
    false
  )
  assert.equal(
    canProcessApprovalRequest(
      { workflowNode: '直属领导审批', person: '张三', managerName: '王总' },
      financeManagerUser
    ),
    false
  )
})

test('direct-manager approval helpers only match claims pushed to the current user', () => {
  const managerUser = { roleCodes: ['manager'], name: '李经理', username: 'manager@example.com' }

  assert.equal(isCurrentRequestApplicant({ person: '李经理', managerName: '王总' }, managerUser), true)
  assert.equal(isCurrentDirectManagerForRequest({ person: '李经理', managerName: '王总' }, managerUser), false)
  assert.equal(isCurrentDirectManagerForRequest({ person: '张三', managerName: '李经理' }, managerUser), true)
  assert.equal(isCurrentDirectManagerForRequest({ person: '张三', managerName: '王总' }, managerUser), false)
})

test('approver executive users can process claims routed to their direct-manager identity', () => {
  const leaderUser = {
    roleCodes: ['approver', 'executive'],
    name: 'Xiang Wanhong',
    username: 'xiangwanhong@xf.com'
  }

  assert.equal(canApproveLeaderExpenseClaims(leaderUser), true)
  assert.equal(
    isCurrentDirectManagerForRequest(
      { person: 'Shen Zhiyuan', managerName: 'Xiang Wanhong' },
      leaderUser
    ),
    true
  )
  assert.equal(
    isCurrentDirectManagerForRequest(
      { person: 'Xiang Wanhong', managerName: 'Li Wenjing' },
      leaderUser
    ),
    false
  )
})

test('applicant helper matches generated draft owner by employee identifiers', () => {
  const currentUser = {
    username: 'caoxiaozhu@xf.com',
    email: 'caoxiaozhu@xf.com',
    employeeNo: 'E90919',
    name: '曹笑竹'
  }

  assert.equal(
    isCurrentRequestApplicant(
      {
        employeeNo: 'E90919',
        employeeName: '曹笑竹',
        person: '曹笑竹'
      },
      currentUser
    ),
    true
  )
  assert.equal(
    isCurrentRequestApplicant(
      {
        employeeNo: 'E10001',
        employeeName: '张三',
        person: '张三'
      },
      currentUser
    ),
    false
  )
})
