import type { JsonObject } from './domain.js'

export type CloudDeliveryPlanItem = {
  cloudSkuId: number
  cloudSkuName: string
  quantity: number
  skuItem: JsonObject | null
  knapsackItem: JsonObject | null
  knapsackCount: number
  missingCount: number
}

export function resolveKuaishouCloudDeliveryPlan(
  flow: JsonObject,
  { skuItems = [], knapsackItems = [] }: { skuItems?: unknown[]; knapsackItems?: unknown[] } = {},
): { items: CloudDeliveryPlanItem[] } {
  const normalizedSkuItems = Array.isArray(skuItems) ? skuItems.filter(isCloudSkuLikeItem) : []
  const normalizedKnapsackItems = Array.isArray(knapsackItems)
    ? knapsackItems.filter(isCloudSkuLikeItem)
    : []
  const deliveryItems = Array.isArray(flow.deliveryItems) ? flow.deliveryItems : []

  return {
    items: deliveryItems
      .map((item: unknown) => {
        const source = item && typeof item === 'object' ? (item as JsonObject) : {}
        const cloudSkuId = Number(source.cloudSkuId || source.skuId || 0) || 0
        const quantity = Number(source.quantity || 1) || 1
        if (!cloudSkuId || !Number.isInteger(quantity) || quantity <= 0) {
          return null
        }

        const skuItem = normalizedSkuItems.find((sku) => Number(sku.id || 0) === cloudSkuId) || null
        const knapsackItem =
          normalizedKnapsackItems.find((sku) => Number(sku.id || 0) === cloudSkuId) || null
        const knapsackCount = Math.max(0, Number(knapsackItem?.count || 0) || 0)
        const cloudSkuName = String(
          source.cloudSkuName || source.skuName || skuItem?.name || knapsackItem?.name || '',
        ).trim()

        return {
          cloudSkuId,
          cloudSkuName,
          quantity,
          skuItem,
          knapsackItem,
          knapsackCount,
          missingCount: Math.max(0, quantity - knapsackCount),
        }
      })
      .filter((item): item is CloudDeliveryPlanItem => Boolean(item)),
  }
}

function isCloudSkuLikeItem(item: unknown): item is JsonObject {
  const current = item && typeof item === 'object' ? (item as JsonObject) : {}
  return Number(current.id || 0) > 0
}
