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

import { syncExpenseClaimFilesToDraft } from '../src/utils/expenseClaimAttachmentSync.js'

function createFile(name) {
  return { name }
}

test('自动归集附件时优先上传到空附件明细项', async () => {
  const uploads = []
  const result = await syncExpenseClaimFilesToDraft({
    claimId: 'claim-1',
    files: [createFile('2月20 武汉-上海.pdf'), createFile('2月23 上海-武汉.pdf')],
    fetchExpenseClaimDetail: async () => ({
      items: [
        { id: 'item-1', invoice_id: '' },
        { id: 'item-2', invoice_id: '' }
      ]
    }),
    createExpenseClaimItem: async () => ({ items: [] }),
    uploadExpenseClaimItemAttachment: async (claimId, itemId, file) => {
      uploads.push({ claimId, itemId, fileName: file.name })
    }
  })

  assert.equal(result.uploadedCount, 2)
  assert.equal(result.skippedCount, 0)
  assert.deepEqual(uploads, [
    { claimId: 'claim-1', itemId: 'item-1', fileName: '2月20 武汉-上海.pdf' },
    { claimId: 'claim-1', itemId: 'item-2', fileName: '2月23 上海-武汉.pdf' }
  ])
})

test('已有明细不足时自动创建明细再上传附件', async () => {
  const uploads = []
  const result = await syncExpenseClaimFilesToDraft({
    claimId: 'claim-1',
    files: [createFile('补充票据.pdf')],
    fetchExpenseClaimDetail: async () => ({ items: [] }),
    createExpenseClaimItem: async () => ({
      items: [{ id: 'created-item-1', invoice_id: '' }]
    }),
    uploadExpenseClaimItemAttachment: async (claimId, itemId, file) => {
      uploads.push({ claimId, itemId, fileName: file.name })
    }
  })

  assert.equal(result.uploadedCount, 1)
  assert.equal(result.skippedCount, 0)
  assert.deepEqual(uploads, [
    { claimId: 'claim-1', itemId: 'created-item-1', fileName: '补充票据.pdf' }
  ])
})
