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

test('agent recharge rejection posts the rejection reason to the order rejection endpoint', async () => {
  const calls = []
  const tempDir = await mkdtemp(join(tmpdir(), 'agent-recharge-service-'))
  const bundlePath = join(tempDir, 'agentRechargeService.mjs')
  const httpMockPath = join(tempDir, 'httpMock.mjs')

  await writeFile(
    httpMockPath,
    `
      export const calls = globalThis.__agentRechargeHttpCalls
      export default {
        post(options) {
          calls.push(options)
          return Promise.resolve({ code: 0, data: undefined })
        }
      }
    `,
    'utf8'
  )

  globalThis.__agentRechargeHttpCalls = calls

  try {
    await esbuild.build({
      entryPoints: ['src/api/modules/agentRecharge.ts'],
      bundle: true,
      outfile: bundlePath,
      format: 'esm',
      platform: 'node',
      absWorkingDir: process.cwd(),
      plugins: [
        {
          name: 'mock-http-boundary',
          setup(build) {
            build.onResolve({ filter: /^@\/utils\/http$/ }, () => ({
              path: httpMockPath
            }))
          }
        }
      ]
    })

    const { AgentRechargeService } = await import(pathToFileURL(bundlePath).href)

    await AgentRechargeService.rejectAgentRecharge(42, {
      rejection_reason: '支付凭证不符合要求'
    })

    assert.deepEqual(calls, [
      {
        url: '/api/admin/agent-recharges/42/reject',
        data: {
          rejection_reason: '支付凭证不符合要求'
        }
      }
    ])
  } finally {
    delete globalThis.__agentRechargeHttpCalls
    await rm(tempDir, { recursive: true, force: true })
  }
})
