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

import {
  TASK_STATUS,
  canRedeemKuaishouCloudClaimStatus,
  isKuaishouCloudRedeemSettledStatus,
} from '../../../domain/task-status.js'
import {
  assertBoundUidMatchesExpected,
  assertClaimExpectedUidReady,
} from '../../claim/claim-identity.js'

/**
 * redeem 用例前置条件单测（不打 DB / CT）。
 * 完整 dispatch 走集成路径；这里锁定状态机与 UID 闸门契约。
 */
function canEnterRedeem(options: {
  status: unknown
  expectedUid: string
  boundUid: string
  mock?: boolean
}) {
  if (isKuaishouCloudRedeemSettledStatus(options.status)) {
    return { ok: true as const, alreadySettled: true }
  }
  if (!canRedeemKuaishouCloudClaimStatus(options.status)) {
    return { ok: false as const, reason: 'status_not_redeemable' }
  }
  if (!options.mock && !options.expectedUid) {
    return { ok: false as const, reason: 'uid_missing' }
  }
  if (!options.mock && options.expectedUid !== options.boundUid) {
    return { ok: false as const, reason: 'uid_mismatch' }
  }
  return { ok: true as const, alreadySettled: false }
}

test('redeem 前置：waiting_binding + uid 匹配可进入', () => {
  const result = canEnterRedeem({
    status: TASK_STATUS.WAITING_BINDING,
    expectedUid: '10001',
    boundUid: '10001',
  })
  assert.deepEqual(result, { ok: true, alreadySettled: false })
})

test('redeem 前置：role_confirmed + uid 匹配可进入', () => {
  const result = canEnterRedeem({
    status: TASK_STATUS.ROLE_CONFIRMED,
    expectedUid: '10001',
    boundUid: '10001',
  })
  assert.deepEqual(result, { ok: true, alreadySettled: false })
})

test('redeem 前置：已 completed 视为 settled', () => {
  const result = canEnterRedeem({
    status: TASK_STATUS.COMPLETED,
    expectedUid: '10001',
    boundUid: '10001',
  })
  assert.deepEqual(result, { ok: true, alreadySettled: true })
})

test('redeem 前置：uid 不一致拒绝', () => {
  const result = canEnterRedeem({
    status: TASK_STATUS.WAITING_BINDING,
    expectedUid: '10001',
    boundUid: '99999',
  })
  assert.equal(result.ok, false)
  if (!result.ok) {
    assert.equal(result.reason, 'uid_mismatch')
  }
})

test('redeem 闸门函数与 claim-identity 一致', () => {
  assert.throws(() => assertClaimExpectedUidReady({ context_json: '{}' }), /填写游戏 UID/)
  assert.throws(
    () =>
      assertBoundUidMatchesExpected(
        {
          context_json: JSON.stringify({
            claimIdentity: { expectedUid: '10001' },
          }),
        },
        {
          binding: { roleId: 'x', roleName: 'n', vnPhone: '1' },
          role: { rid: 'x', name: 'n' },
        },
      ),
    /不一致/,
  )
})
