import test from 'node:test'
import assert from 'node:assert/strict'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import * as esbuild from 'esbuild'

async function importBundledDisplay() {
  const tempDir = await mkdtemp(join(tmpdir(), 'agent-recharge-display-'))
  const bundlePath = join(tempDir, 'agentRechargeDisplay.mjs')

  await esbuild.build({
    entryPoints: ['src/views/finance/agent-recharge/agentRechargeDisplay.ts'],
    bundle: true,
    outfile: bundlePath,
    format: 'esm',
    platform: 'node',
    absWorkingDir: process.cwd()
  })

  const module = await import(pathToFileURL(bundlePath).href)
  return {
    module,
    cleanup: () => rm(tempDir, { recursive: true, force: true })
  }
}

test('agent recharge rejection reason display uses backend rejection_reason when present', async () => {
  const { module, cleanup } = await importBundledDisplay()

  try {
    assert.equal(module.formatRejectionReason('凭证不清晰'), '凭证不清晰')
  } finally {
    await cleanup()
  }
})

test('agent recharge rejection reason display falls back to dash when absent', async () => {
  const { module, cleanup } = await importBundledDisplay()

  try {
    assert.equal(module.formatRejectionReason(''), '-')
    assert.equal(module.formatRejectionReason(null), '-')
    assert.equal(module.formatRejectionReason(undefined), '-')
  } finally {
    await cleanup()
  }
})
