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

import {
  ADMIN_OBSERVED_PRODUCTS_QUERY,
  listAdminObservedProducts,
  mapAdminObservedProductRow,
} from './observed-products.js'

test('mapAdminObservedProductRow normalizes query row fields', () => {
  assert.deepEqual(
    mapAdminObservedProductRow({
      provider: ' agiso ',
      platform: ' xianyu ',
      shop_id: ' shop-1 ',
      shop_name: ' 店铺A ',
      external_item_id: ' item-1 ',
      external_sku_code: ' sku-1 ',
      external_sku_name: ' 商品A ',
      latest_seen_at: '2026-05-04T12:00:00.000Z',
      order_item_count: '3',
    }),
    {
      provider: 'agiso',
      platform: 'xianyu',
      shopId: 'shop-1',
      shopName: '店铺A',
      externalItemId: 'item-1',
      externalSkuCode: 'sku-1',
      externalSkuName: '商品A',
      latestSeenAt: '2026-05-04T12:00:00.000Z',
      orderItemCount: 3,
    },
  )
})

test('listAdminObservedProducts queries rows and maps matched binding summary', async () => {
  /** @type {string[]} */
  const sqlCalls = []
  const result = await listAdminObservedProducts(
    [
      {
        provider: 'agiso',
        platform: 'xianyu',
        shopId: 'shop-1',
        skuCode: 'inner-1',
        skuName: '内部商品A',
        profileKey: 'manual_review',
        match: {
          externalSkuCode: 'sku-1',
        },
      },
    ],
    {
      async query(sql) {
        sqlCalls.push(sql)
        return {
          rows: [
            {
              provider: 'agiso',
              platform: 'xianyu',
              shop_id: 'shop-1',
              shop_name: '店铺A',
              external_item_id: '',
              external_sku_code: 'sku-1',
              external_sku_name: '商品A',
              latest_seen_at: '2026-05-04T12:00:00.000Z',
              order_item_count: 2,
            },
          ],
        }
      },
    },
  )

  assert.equal(sqlCalls.length, 1)
  assert.equal(sqlCalls[0], ADMIN_OBSERVED_PRODUCTS_QUERY)
  assert.deepEqual(result, [
    {
      provider: 'agiso',
      platform: 'xianyu',
      shopId: 'shop-1',
      shopName: '店铺A',
      externalItemId: '',
      externalSkuCode: 'sku-1',
      externalSkuName: '商品A',
      latestSeenAt: '2026-05-04T12:00:00.000Z',
      orderItemCount: 2,
      configured: true,
      matchedBinding: {
        skuCode: 'inner-1',
        skuName: '内部商品A',
        profileKey: 'manual_review',
      },
    },
  ])
})
