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

import { buildOpen91SourceEvent, parseOpen91ProductNo } from './order-service.js'

test('buildOpen91SourceEvent maps 91 productNo into source item identities', () => {
  const event = buildOpen91SourceEvent(
    {
      orderNo: 'P91KS202605130001',
      productNo: 'KS-CLOUD-SKU-001',
      buyNum: 2,
      maxAmount: '0.01',
      timestamp: 1778670308,
      version: '1.0',
      sign: 'SIGN',
    },
    {
      shopId: '91kaquan',
      shopName: '91卡券',
    },
  )

  assert.equal(event.provider, '91kaquan')
  assert.equal(event.platform, 'kuaishou')
  assert.equal(event.shopId, '91kaquan')
  assert.equal(event.platformOrderId, 'P91KS202605130001')
  assert.equal(event.payStatus, 'paid')
  assert.equal(event.items.length, 1)
  assert.equal(event.items[0].externalItemId, 'KS-CLOUD-SKU-001')
  assert.equal(event.items[0].externalSkuCode, 'KS-CLOUD-SKU-001')
  assert.equal(event.items[0].externalSkuName, 'KS-CLOUD-SKU-001')
  assert.equal(event.items[0].quantity, 2)
  assert.equal(event.items[0].snapshot.productNo, 'KS-CLOUD-SKU-001')
})

test('parseOpen91ProductNo splits product name and kuaishou shop id by four dashes', () => {
  assert.deepEqual(parseOpen91ProductNo('测试-关联商品1----3676797936'), {
    rawProductNo: '测试-关联商品1----3676797936',
    productName: '测试-关联商品1',
    shopId: '3676797936',
  })
})

test('buildOpen91SourceEvent keeps productNo suffix for kuaishou consume only', () => {
  const event = buildOpen91SourceEvent(
    {
      orderNo: 'P91KS202605130002',
      productNo: '测试-关联商品1----3676797936',
      buyNum: 1,
      maxAmount: '0.01',
      timestamp: 1778670308,
      version: '1.0',
      sign: 'SIGN',
    },
    {
      shopId: '91kaquan',
      shopName: '91卡券',
    },
  )

  assert.equal(event.shopId, '91kaquan')
  assert.equal(event.shopName, '91卡券')
  assert.equal(event.items[0].externalItemId, '测试-关联商品1----3676797936')
  assert.equal(event.items[0].externalSkuCode, '测试-关联商品1----3676797936')
  assert.equal(event.items[0].externalSkuName, '测试-关联商品1')
  assert.equal(event.items[0].skuCode, '测试-关联商品1')
  assert.equal(event.items[0].skuName, '测试-关联商品1')
  assert.equal(event.items[0].snapshot.productNo, '测试-关联商品1----3676797936')
  assert.equal(event.items[0].snapshot.productName, '测试-关联商品1')
  assert.equal(event.items[0].snapshot.shopId, '3676797936')
  assert.equal(event.items[0].spec.shopId, '3676797936')
})
