import { createHttpError } from '../../../utils/http.js'
import { cloudtentaclesRequest } from './http-client.js'
import { resolveCloudtentaclesConfig } from './helpers.js'
import type { JsonObject } from '../../../types/json.js'

export async function getCloudtentaclesKnapsack(payload: JsonObject = {}) {
  const token = String(payload.token || '').trim()
  if (!token) {
    throw createHttpError('cloudtentacles 背包查询缺少 token', {
      statusCode: 400,
      errorCode: 'cloudtentacles_knapsack_missing_token',
    })
  }

  const config = resolveCloudtentaclesConfig(payload)
  const result = await cloudtentaclesRequest(config.knapsackPath, {
    ...config,
    method: 'GET',
    token,
    contentType: 'application/json',
    sourceKey: payload.sourceKey || payload.resolvedSourceKey,
    accountLabel: payload.accountLabel,
    context: {
      operation: 'knapsack_get',
      sourceKey: payload.sourceKey || payload.resolvedSourceKey || '',
    },
    businessErrorStatusCode: 401,
    businessErrorCode: 'cloudtentacles_knapsack_failed',
  })

  const items = Array.isArray(result.payload?.data) ? result.payload.data.map(mapKnapsackItem) : []

  return {
    baseUrl: config.baseUrl,
    itemCount: items.length,
    items,
    rawItems: Array.isArray(result.payload?.data) ? result.payload.data : [],
  }
}

function mapKnapsackItem(item: unknown) {
  const source = isPlainObject(item) ? item : {}

  return {
    id: Number(source.id || 0),
    name: String(source.name || '').trim(),
    count: Number(source.count || 0),
    image: String(source.image || '').trim(),
    categoriesId: Number(source.categories_id || 0),
    listingTime: String(source.listing_time || '').trim(),
    delistingTime: String(source.delisting_time || '').trim(),
    raw: source,
  }
}

function isPlainObject(value: unknown): value is JsonObject {
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
}
