import { mapExpenseClaimToRequest } from '../composables/useRequests.js'
import {
  canApproveBudgetExpenseApplications,
  canApproveLeaderExpenseClaims,
  isCurrentDirectManagerForRequest,
  isCurrentRequestApplicant,
  isFinanceUser
} from './accessControl.js'

export function canProcessApprovalRequest(request, currentUser) {
  const node = String(request?.workflowNode || '').trim()

  if (isCurrentRequestApplicant(request, currentUser)) {
    return false
  }

  if (isFinanceUser(currentUser) && node.includes('财务')) {
    return true
  }

  if (node.includes('预算')) {
    return canApproveBudgetExpenseApplications(currentUser, request)
  }

  const isLeaderApprovalNode = (
    node.includes('直属领导')
    || node.includes('领导审批')
    || node.includes('部门负责人')
    || node.includes('负责人审批')
  )

  return (
    canApproveLeaderExpenseClaims(currentUser)
    && isLeaderApprovalNode
    && isCurrentDirectManagerForRequest(request, currentUser)
  )
}

export function listPendingApprovalRequests(claimsPayload, currentUser) {
  if (!Array.isArray(claimsPayload)) {
    return []
  }

  return claimsPayload
    .map((item) => mapExpenseClaimToRequest(item))
    .filter((item) => item.approvalKey === 'in_progress')
    .filter((item) => canProcessApprovalRequest(item, currentUser))
}

export function resolvePendingClaimIds(claimsPayload, currentUser) {
  return listPendingApprovalRequests(claimsPayload, currentUser)
    .map((item) => String(item.claimId || '').trim())
    .filter(Boolean)
}
