import { ref } from 'vue'

import {
  REIMBURSEMENT_LIST_PREVIEW_PARAMS,
  extractExpenseClaimItems,
  fetchArchivedExpenseClaims
} from '../services/reimbursements.js'
import { buildDocumentRow } from '../utils/documentCenterViewModel.js'
import { mapExpenseClaimToRequest } from './useRequests.js'

export function useDocumentCenterArchiveRows(options = {}) {
  const archiveRows = ref([])
  const supportingLoading = ref(false)
  const supportingError = ref('')
  let requestSequence = 0

  async function loadSupportingRows() {
    const sequence = ++requestSequence
    supportingLoading.value = true
    supportingError.value = ''
    try {
      const payload = await fetchArchivedExpenseClaims(REIMBURSEMENT_LIST_PREVIEW_PARAMS)
      if (sequence !== requestSequence) return
      archiveRows.value = extractExpenseClaimItems(payload)
        .map(mapExpenseClaimToRequest)
        .map((item) => buildDocumentRow(item, {
          source: 'archive',
          archived: true,
          currentUser: options.currentUser?.value,
          viewedDocumentKeys: options.viewedDocumentKeys?.value
        }))
        .filter(Boolean)
    } catch (error) {
      if (sequence !== requestSequence) return
      archiveRows.value = []
      supportingError.value = error?.message || '归档数据加载失败。'
    } finally {
      if (sequence === requestSequence) supportingLoading.value = false
    }
  }

  return { archiveRows, supportingError, supportingLoading, loadSupportingRows }
}
