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

import {
  buildFulfillmentLookupResult,
  normalizeFulfillmentLookupPayload,
  resolveFulfillmentLookupDetail,
} from './fulfillment.js'

test('normalizeFulfillmentLookupPayload validates required fields and defaults provider/platform', () => {
  assert.deepEqual(
    normalizeFulfillmentLookupPayload({
      shopId: ' shop-1 ',
      platformOrderId: ' order-1 ',
    }),
    {
      provider: 'agiso',
      platform: 'xianyu',
      shopId: 'shop-1',
      platformOrderId: 'order-1',
    },
  )

  assert.throws(
    () => normalizeFulfillmentLookupPayload({ platformOrderId: 'order-1' }),
    /请先填写店铺 ID/,
  )
})

test('resolveFulfillmentLookupDetail maps missing config into readable error', () => {
  assert.throws(
    () =>
      resolveFulfillmentLookupDetail(
        {
          reason: 'missing_config',
          parsed: { items: [] },
        },
        'order-1',
      ),
    /当前店铺缺少订单详情查询配置/,
  )
})

test('buildFulfillmentLookupResult assembles order and item matching payload', () => {
  const result = buildFulfillmentLookupResult({
    provider: 'agiso',
    platform: 'xianyu',
    shopId: 'shop-1',
    platformOrderId: 'order-1',
    detail: {
      shopName: '店铺A',
      buyerName: '买家A',
      totalAmount: 12345,
      paidAt: '2026-05-04T10:00:00.000Z',
      items: [
        {
          externalItemId: 'item-1',
          externalSkuCode: 'sku-1',
          externalSkuName: '礼包A',
          skuName: '礼包A',
          quantity: 2,
        },
      ],
    },
    detailResult: {
      enriched: true,
      reason: 'ok',
      errorMessage: '',
    },
    bindings: [
      {
        provider: 'agiso',
        platform: 'xianyu',
        shopId: 'shop-1',
        skuCode: 'internal-1',
        skuName: '内部商品',
        profileKey: 'profile-1',
        match: {
          externalSkuCode: 'sku-1',
        },
      },
    ],
    fallbackShopName: '备用店铺',
  })

  assert.deepEqual(result, {
    order: {
      provider: 'agiso',
      platform: 'xianyu',
      shopId: 'shop-1',
      shopName: '店铺A',
      platformOrderId: 'order-1',
      buyerName: '买家A',
      totalAmountFen: 12345,
      totalAmount: '123.45',
      paidAt: '2026-05-04T10:00:00.000Z',
      enriched: true,
      enrichReason: 'ok',
      errorMessage: '',
    },
    items: [
      {
        lineId: 'order-1:1:sku-1:item-1',
        itemTitle: '礼包A',
        quantity: 2,
        provider: 'agiso',
        platform: 'xianyu',
        shopId: 'shop-1',
        shopName: '店铺A',
        externalItemId: 'item-1',
        externalSkuCode: 'sku-1',
        externalSkuName: '礼包A',
        latestSeenAt: null,
        orderItemCount: 2,
        configured: true,
        matchedBinding: {
          skuCode: 'internal-1',
          skuName: '内部商品',
          profileKey: 'profile-1',
        },
      },
    ],
  })
})
