import { isApplicationRequestLike } from './documentClassification.js'

const ARCHIVED_CLAIM_STATUSES = new Set(['approved', 'completed', 'paid'])
const APPLICATION_ARCHIVE_STAGE = '申请归档'

function isArchivedRequestPayload(request) {
  if (!request) {
    return false
  }

  const normalizedStatus = String(request.status || '').trim().toLowerCase()
  const stage = String(request.approval_stage || request.approvalStage || '').trim()
  const isApplicationRequest = isApplicationRequestLike(request)

  if (isApplicationRequest) {
    return ARCHIVED_CLAIM_STATUSES.has(normalizedStatus) && stage === APPLICATION_ARCHIVE_STAGE
  }

  if (stage === '归档入账' || stage === '已付款' || stage === 'completed') {
    return true
  }

  if (stage.includes('归档') || stage.includes('入账')) {
    return true
  }

  return ARCHIVED_CLAIM_STATUSES.has(normalizedStatus)
    && (stage === '' || stage === '归档入账' || stage === '已付款' || stage === 'completed')
}

export function isArchivedDocumentRow(row) {
  if (!row) {
    return false
  }

  if (row.archived === true) {
    return true
  }

  return isArchivedRequestPayload(row.rawRequest || row)
}

export function excludeArchivedDocumentRows(rows) {
  return (Array.isArray(rows) ? rows : []).filter((row) => !isArchivedDocumentRow(row))
}

export function isApplicationApprovalRow(row) {
  if (!row) {
    return false
  }

  const statusGroup = String(row.statusGroup || '').trim()
  return statusGroup === 'in_progress' && isApplicationRequestLike(row.rawRequest || row)
}

export function filterApplicationScopeNewRows(rows) {
  return (Array.isArray(rows) ? rows : []).filter((row) => !isApplicationApprovalRow(row))
}

export function prepareApplicationScopeRows(rows) {
  return (Array.isArray(rows) ? rows : [])
    .filter((row) => isApplicationRequestLike(row.rawRequest || row))
    .map((row) => (isApplicationApprovalRow(row) ? { ...row, isNewDocument: false } : row))
}
