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

import {
  hasKuaishouCloudCustomerRole,
  hasKuaishouCloudDefaultRoleSnapshot,
  isSameKuaishouCloudRoleIdentity,
} from './domain.js'
import { buildRoleStateFromCurrentInfo } from './role-state.js'
import { normalizeKuaishouCloudFlow } from './domain.js'

test('hasKuaishouCloudCustomerRole 只要求已有绑定角色信息（UID 主闸后默认角色不再作门槛）', () => {
  const defaultRoleFlow = {
    binding: {
      vnPhone: '13800000000',
      roleName: '默认机位角色',
      roleId: 'DEFAULT-000',
    },
    role: {
      defaultName: '默认机位角色',
      defaultRid: 'DEFAULT-000',
    },
  }

  assert.equal(hasKuaishouCloudCustomerRole(defaultRoleFlow), true)
  assert.equal(hasKuaishouCloudDefaultRoleSnapshot(defaultRoleFlow), true)

  const emptyFlow = {
    binding: {
      vnPhone: '13800000000',
      roleName: '',
      roleId: '',
    },
  }
  assert.equal(hasKuaishouCloudCustomerRole(emptyFlow), false)
})

test('buildRoleStateFromCurrentInfo 即使接近默认角色也 ready 并保留 rid', () => {
  const flow = normalizeKuaishouCloudFlow({
    role: {
      defaultName: '默认机位角色',
      defaultRid: 'DEFAULT-000',
    },
    binding: {},
  })
  const state = buildRoleStateFromCurrentInfo({
    flow,
    roleInfo: { name: '默认机位角色', rid: 'DEFAULT-000' },
    now: '2026-07-10T00:00:00.000Z',
    emptyMessage: 'empty',
  })

  assert.equal(state.hasRoleInfo, true)
  assert.equal(state.isDefaultRole, true)
  assert.equal(state.role.status, 'ready')
  assert.equal(state.bindingRoleId, 'DEFAULT-000')
  assert.match(state.role.errorMessage, /UID/)
})

test('isSameKuaishouCloudRoleIdentity prefers rid', () => {
  assert.equal(
    isSameKuaishouCloudRoleIdentity({ name: 'a', rid: '1' }, { name: 'b', rid: '1' }),
    true,
  )
  assert.equal(
    isSameKuaishouCloudRoleIdentity({ name: 'a', rid: '1' }, { name: 'a', rid: '2' }),
    false,
  )
})
