import { createHttpError } from '../../../utils/http.js'
import type { HttpErrorLike } from '../../../utils/http.js'
import type { JsonObject } from '../../../types/json.js'
import { resolvePersistedCloudtentaclesContextBySourceKeys } from '../../fulfillment/kuaishou-cloud/cloudtentacles-context.js'

export type { JsonObject }

export {
  KUAISHOU_CLOUD_FIXED_VN_KEY,
  isKuaishouCloudTask,
  normalizeKuaishouCloudFlow,
  normalizeKuaishouCloudRoleInfo,
  resolveKuaishouCloudBindUrlExpiresAt,
} from '../../fulfillment/kuaishou-cloud/domain.js'
export {
  prepareKuaishouCloudBindResourceWithFallback,
  resolveKuaishouCloudBindingResources,
  resolveKuaishouCloudVnKeyCandidates,
} from '../../fulfillment/kuaishou-cloud/binding-resources.js'

export type CloudtentaclesContext = {
  baseUrl: string
  token: string
  deviceId: string
  deviceType: number
  resolvedSourceKey: string
}

export type CloudSkuLikeItem = {
  id?: number | string
  name?: string
  price?: number | string
  count?: number | string
  [key: string]: unknown
}

export type { KuaishouCloudFlow } from '../../fulfillment/kuaishou-cloud/domain.js'

export type KuaishouCloudBindingResources = {
  skuId: number
  skuName: string
  vnKey: string
  skuItem: CloudSkuLikeItem | null
  knapsackItem: CloudSkuLikeItem | null
  resolvedByName: boolean
}

export type PreparedKuaishouCloudBindResource = {
  vnKey: string
  vnId: number
  vnPhone: string
  bindUrl: string
}

export function resolvePersistedCloudtentaclesContext(
  sourceKeys: unknown[],
): CloudtentaclesContext {
  try {
    return resolvePersistedCloudtentaclesContextBySourceKeys(sourceKeys)
  } catch (error) {
    if (isMissingCloudtentaclesTokenError(error)) {
      throw createHttpError('当前 cloudtentacles 没有可用 token，请先到平台配置完成登录校验', {
        statusCode: 409,
        errorCode: 'admin_task_kuaishou_cloud_missing_cloud_token',
        cause: error,
      })
    }

    throw error
  }
}

function isMissingCloudtentaclesTokenError(error: unknown): boolean {
  const current = error as HttpErrorLike | null
  return String(current?.errorCode || '').trim() === 'kuaishou_cloud_missing_cloud_token'
}
