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

import { TASK_STATUS } from '../../../domain/task-status.js'
import {
  buildKuaishouCloudShippedSnapshot,
  isKuaishouCloudBindingMutationFrozen,
  isKuaishouCloudDispatchSucceeded,
  normalizeKuaishouCloudFlow,
} from './domain.js'

test('isKuaishouCloudDispatchSucceeded 识别 dispatch.success', () => {
  assert.equal(isKuaishouCloudDispatchSucceeded({ dispatch: { status: 'success' } }), true)
  assert.equal(isKuaishouCloudDispatchSucceeded({ dispatch: { status: 'pending' } }), false)
})

test('isKuaishouCloudBindingMutationFrozen：dispatch.success 即使 status=waiting_binding 也冻结', () => {
  assert.equal(
    isKuaishouCloudBindingMutationFrozen(
      { task_status: TASK_STATUS.WAITING_BINDING },
      { dispatch: { status: 'success' } },
    ),
    true,
  )
})

test('isKuaishouCloudBindingMutationFrozen：兑换中/已完成冻结', () => {
  assert.equal(
    isKuaishouCloudBindingMutationFrozen(
      { task_status: TASK_STATUS.REDEEMING },
      { dispatch: { status: 'pending' } },
    ),
    true,
  )
  assert.equal(
    isKuaishouCloudBindingMutationFrozen(
      { task_status: TASK_STATUS.COMPLETED },
      { dispatch: { status: 'pending' } },
    ),
    true,
  )
})

test('isKuaishouCloudBindingMutationFrozen：待绑定未发货不冻结', () => {
  assert.equal(
    isKuaishouCloudBindingMutationFrozen(
      { task_status: TASK_STATUS.WAITING_BINDING },
      { dispatch: { status: 'pending' } },
    ),
    false,
  )
})

test('normalizeKuaishouCloudFlow 保留 shipped 快照', () => {
  const flow = normalizeKuaishouCloudFlow({
    dispatch: { status: 'success' },
    shipped: {
      expectedUid: '3781015014',
      roleId: '3781015014',
      roleName: 'l迈',
      vnId: 189363,
      vnPhone: '18641685924',
      vnKey: '1',
      dispatchedAt: '2026-07-16T06:25:13.000Z',
    },
    binding: { roleId: '3805904834', roleName: '他爆炸' },
  })
  assert.equal(flow.shipped?.roleId, '3781015014')
  assert.equal(flow.shipped?.expectedUid, '3781015014')
  assert.equal(flow.binding.roleId, '3805904834')
})

test('buildKuaishouCloudShippedSnapshot 固化发货身份', () => {
  const snapshot = buildKuaishouCloudShippedSnapshot({
    expectedUid: '3781015014',
    roleId: '3781015014',
    roleName: '安卓-微信-l迈',
    vnId: 189363,
    vnPhone: '18641685924',
    dispatchedAt: 'now',
  })
  assert.deepEqual(snapshot, {
    expectedUid: '3781015014',
    roleId: '3781015014',
    roleName: '安卓-微信-l迈',
    vnId: 189363,
    vnPhone: '18641685924',
    vnKey: '1',
    dispatchedAt: 'now',
  })
})
