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

import {
  isCloudtentaclesPermissionLikeError,
  wrapCloudtentaclesOperationError,
} from './cloudtentacles-errors.js'

test('wrapCloudtentaclesOperationError 把权限不足包装成可定位文案', () => {
  const upstream = Object.assign(new Error('权限不足'), {
    statusCode: 401,
    errorCode: 'cloudtentacles_vn_back_failed',
    context: {
      upstreamCode: -1,
      upstreamMessage: '权限不足',
      upstreamPayload: { code: -1, message: '权限不足' },
    },
  })

  const wrapped = wrapCloudtentaclesOperationError(upstream, {
    action: 'vn_back',
    actionLabel: '退还旧虚拟号',
    sourceKey: 'account_day',
    vnKey: '1',
    vnId: 12345,
    vnPhone: '13800000000',
  }) as Error & { statusCode?: number; errorCode?: string }

  assert.equal(wrapped.statusCode, 409)
  assert.match(wrapped.message, /cloudtentacles 退还旧虚拟号失败/)
  assert.match(wrapped.message, /上游：权限不足/)
  assert.match(wrapped.message, /账号=account_day/)
  assert.match(wrapped.message, /vnId=12345/)
  assert.match(wrapped.message, /平台配置/)
  assert.equal(isCloudtentaclesPermissionLikeError(upstream), true)
})

test('isCloudtentaclesPermissionLikeError 识别权限类文案', () => {
  assert.equal(isCloudtentaclesPermissionLikeError(new Error('权限不足')), true)
  assert.equal(isCloudtentaclesPermissionLikeError(new Error('余额不足')), false)
})
