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

/** lewan 发货单元：一次下发的 cloud SKU */
export type DispatchDeliveryItem = {
  cloudSkuId: number
  cloudSkuName: string
  quantity: number
}

export type DispatchResultItem = DispatchDeliveryItem & {
  unitIndex: number
  sendType: number
  note: string
  responseMessage: string
}

export type DispatchStockItem = DispatchDeliveryItem & {
  requiredCount: number
  knapsackCount: number
  purchasedCount: number
}

export type DispatchStockResult = {
  usedKnapsack: boolean
  purchaseTriggered: boolean
  assetBefore: number
  assetAfter: number
  items: DispatchStockItem[]
}

export function resolveDispatchDeliveryItems(flow: JsonObject): DispatchDeliveryItem[] {
  const rawItems = Array.isArray(flow.deliveryItems) ? flow.deliveryItems : []
  const items = rawItems
    .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 (!Number.isInteger(cloudSkuId) || cloudSkuId <= 0) {
        return null
      }

      return {
        cloudSkuId,
        cloudSkuName: String(source.cloudSkuName || source.skuName || '').trim(),
        quantity: Number.isInteger(quantity) && quantity > 0 ? quantity : 1,
      }
    })
    .filter((item): item is DispatchDeliveryItem => Boolean(item))

  if (items.length > 0) {
    return items
  }

  const binding =
    flow.binding && typeof flow.binding === 'object' ? (flow.binding as JsonObject) : {}
  const fallbackSkuId = Number(binding.skuId || 0) || 0
  if (!fallbackSkuId) {
    return []
  }

  return [
    {
      cloudSkuId: fallbackSkuId,
      cloudSkuName: String(binding.skuName || '').trim(),
      quantity: 1,
    },
  ]
}
