import test from 'node:test'
import assert from 'node:assert/strict'
import { mkdtemp, rm, stat } 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 resolveSrcAlias(path) {
  const resolvedPath = join(process.cwd(), 'src', path.slice(2))

  try {
    if ((await stat(resolvedPath)).isDirectory()) {
      return join(resolvedPath, 'index.ts')
    }
  } catch {
    // Let esbuild report the original resolution failure.
  }

  return resolvedPath
}

async function importBundledActions() {
  const tempDir = await mkdtemp(join(tmpdir(), 'agent-recharge-actions-'))
  const bundlePath = join(tempDir, 'agentRechargeActions.mjs')

  await esbuild.build({
    entryPoints: ['src/views/finance/agent-recharge/agentRechargeActions.ts'],
    bundle: true,
    outfile: bundlePath,
    format: 'esm',
    platform: 'node',
    absWorkingDir: process.cwd(),
    plugins: [
      {
        name: 'alias-src',
        setup(build) {
          build.onResolve({ filter: /^@\// }, async (args) => ({
            path: await resolveSrcAlias(args.path)
          }))
        }
      }
    ]
  })

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

test('pending agent recharge exposes reject action for admins with rejection permission', async () => {
  const { module, cleanup } = await importBundledActions()
  const { buildAgentRechargeActions } = module
  const row = {
    id: 42,
    status: 1,
    payment_method: 'wechat',
    payment_voucher_key: []
  }
  const handledRows = []

  try {
    const actions = buildAgentRechargeActions(row, {
      hasAuth: (permission) => permission === 'agent_recharge:reject',
      onViewPaymentVoucher: () => {},
      onConfirmPayment: () => {},
      onReject: (recharge) => handledRows.push(recharge)
    })

    assert.deepEqual(
      actions.map((action) => action.label),
      ['拒绝']
    )

    actions[0].handler()

    assert.deepEqual(handledRows, [row])
  } finally {
    await cleanup()
  }
})

test('non-pending agent recharge does not expose reject action', async () => {
  const { module, cleanup } = await importBundledActions()
  const { buildAgentRechargeActions } = module
  const row = {
    id: 42,
    status: 2,
    payment_method: 'wechat',
    payment_voucher_key: []
  }

  try {
    const actions = buildAgentRechargeActions(row, {
      hasAuth: (permission) => permission === 'agent_recharge:reject',
      onViewPaymentVoucher: () => {},
      onConfirmPayment: () => {},
      onReject: () => {}
    })

    assert.deepEqual(
      actions.map((action) => action.label),
      []
    )
  } finally {
    await cleanup()
  }
})
