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

import { resolveRedeemProofMode, shouldCaptureBeijingTimeProof } from './session-proof.js'
import { buildProofHtml } from './session-proof-html.js'
import { buildArtifactPaths } from './session-proof-paths.js'

test('resolveRedeemProofMode normalizes configured modes and falls back to full', () => {
  assert.equal(resolveRedeemProofMode('basic'), 'basic')
  assert.equal(resolveRedeemProofMode(' OFF '), 'off')
  assert.equal(resolveRedeemProofMode('full'), 'full')
  assert.equal(resolveRedeemProofMode('unexpected'), 'full')
  assert.equal(resolveRedeemProofMode(''), 'full')
})

test('shouldCaptureBeijingTimeProof only returns true for successful redeem results', () => {
  assert.equal(
    shouldCaptureBeijingTimeProof({
      classification: {
        success: true,
      },
    }),
    true,
  )

  assert.equal(
    shouldCaptureBeijingTimeProof({
      classification: {
        success: false,
      },
    }),
    false,
  )

  assert.equal(
    shouldCaptureBeijingTimeProof({
      redeem: {
        iRet: 0,
      },
    }),
    true,
  )

  assert.equal(
    shouldCaptureBeijingTimeProof({
      redeem: {
        iRet: -183,
      },
    }),
    false,
  )

  assert.equal(shouldCaptureBeijingTimeProof(null), false)
})

test('buildArtifactPaths keeps redeem proof artifact filenames stable', () => {
  const artifactPaths = buildArtifactPaths('/tmp/redeem-proof')

  assert.equal(artifactPaths.redeemPageScreenshotPath, path.join('/tmp/redeem-proof', 'redeem-page.png'))
  assert.equal(artifactPaths.beijingTimeScreenshotPath, path.join('/tmp/redeem-proof', 'beijing-time.png'))
  assert.equal(artifactPaths.screenshotPath, path.join('/tmp/redeem-proof', 'redeem-result.png'))
  assert.equal(artifactPaths.htmlPath, path.join('/tmp/redeem-proof', 'page.html'))
  assert.equal(artifactPaths.resultPath, path.join('/tmp/redeem-proof', 'result.json'))
})

test('buildProofHtml escapes injected text while keeping proof sections stable', () => {
  const html = buildProofHtml({
    redeemImageBase64: 'redeem-base64',
    timeImageBase64: 'time-base64',
    redeemMessage: '<b>兑换成功 & 已到账</b>',
    timePageUrl: 'https://example.com/?q=<北京时间>',
  })

  assert.match(html, /Tencent Redeem Proof/)
  assert.match(html, /兑换截图与北京时间截图/)
  assert.match(html, /&lt;b&gt;兑换成功 &amp; 已到账&lt;\/b&gt;/)
  assert.match(html, /https:\/\/example\.com\/\?q=&lt;北京时间&gt;/)
  assert.match(html, /data:image\/png;base64,redeem-base64/)
  assert.match(html, /data:image\/png;base64,time-base64/)
})
