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

import {
  classifyTencentRedeemResult,
  isCaptchaRejectedResult,
  resolveTencentRedeemMessage,
} from './session-redeem.js'

test('resolveTencentRedeemMessage prefers popup detail over generic title', () => {
  assert.equal(
    resolveTencentRedeemMessage({
      popup: {
        text: '兑换结果',
        detail: '兑换码错误，请确认兑换码信息是否准确。',
      },
    }),
    '兑换码错误，请确认兑换码信息是否准确。',
  )
})

test('classifyTencentRedeemResult marks used codes as replacement retries', () => {
  const result = classifyTencentRedeemResult({
    popup: {
      text: '兑换结果',
      detail: '兑换码已使用。',
    },
  })

  assert.equal(result.outcome, 'code_used')
  assert.equal(result.success, false)
  assert.equal(result.retryWithReplacementCode, true)
})

test('classifyTencentRedeemResult marks invalid codes as replacement retries', () => {
  const result = classifyTencentRedeemResult({
    popup: {
      text: '兑换结果',
      detail: '兑换码错误，请确认兑换码信息是否准确。',
    },
  })

  assert.equal(result.outcome, 'code_invalid')
  assert.equal(result.success, false)
  assert.equal(result.retryWithReplacementCode, true)
})

test('classifyTencentRedeemResult treats missing CDKEY responses as invalid replacement retries', () => {
  const result = classifyTencentRedeemResult({
    iRet: -183,
    sMsg: '该CDKEY不存在，请您确认后输入!',
  })

  assert.equal(result.outcome, 'code_invalid')
  assert.equal(result.success, false)
  assert.equal(result.retryWithReplacementCode, true)
})

test('classifyTencentRedeemResult recognizes successful gift popup', () => {
  const result = classifyTencentRedeemResult({
    popup: {
      text: '恭喜您获得了礼包：动作-干员庆生，请注意：游戏虚拟道具奖品将会在24小时内到账，请登录游戏查看邮件。',
      detail: '',
    },
  })

  assert.equal(result.outcome, 'success')
  assert.equal(result.success, true)
})

test('isCaptchaRejectedResult only treats captcha problems as same-code retries', () => {
  assert.equal(
    isCaptchaRejectedResult({
      iRet: -100,
      sMsg: '验证码错误',
    }),
    true,
  )

  assert.equal(
    isCaptchaRejectedResult({
      popup: {
        text: '兑换结果',
        detail: '兑换码已使用。',
      },
    }),
    false,
  )
})
