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

import { planFulfillmentTaskForOrderItem } from './planner.js'
import type { OrderItemRow, OrderRow } from '../../types/repository/rows.js'

test('planFulfillmentTaskForOrderItem 为 cloudtentacles 商品生成 kuaishou-lewan 履约计划', async () => {
  const plan = await planFulfillmentTaskForOrderItem({
    order: createOrder(),
    item: createOrderItem({
      sku_code: '荣耀勋章礼包（30个）',
      sku_name: '荣耀勋章礼包（30个）',
      item_snapshot_json: {
        cloudtentacles: {
          matchMode: 'cloudtentacles_name',
          normalizedProductName: '荣耀勋章礼包(30个)',
          cloudSourceKeys: ['account-a'],
          cloudSkuId: 74,
          cloudSkuName: '荣耀勋章礼包（30个）',
        },
      },
    }),
    getProfileByKey: async (profileKey) => ({
      id: 9,
      profile_key: profileKey,
      name: 'kuaishou-lewan 履约',
      executor_key: profileKey,
      requires_claim: true,
      auto_dispatch: true,
    }),
  })

  assert.ok(plan)
  assert.equal(plan.executorKey, 'kuaishou_ct_assisted')
  assert.equal(plan.requiresClaim, false)
  assert.equal(plan.autoDispatch, false)
  assert.equal(plan.context.profileKey, 'kuaishou_ct_assisted')
  assert.equal(
    (plan.context.kuaishouCloudFulfillment as any).binding.resolvedSourceKey,
    'account-a',
  )
  assert.equal((plan.context.kuaishouCloudFulfillment as any).binding.skuId, 74)
  assert.equal(plan.context.kuaishouFeifei, null)
})

test('planFulfillmentTaskForOrderItem 为 feifei 商品生成 feifei 履约计划', async () => {
  const plan = await planFulfillmentTaskForOrderItem({
    order: createOrder(),
    item: createOrderItem({
      sku_code: 'FF-1001',
      sku_name: '测试皮肤',
      item_snapshot_json: {
        kuaishouFeifei: {
          productCode: 'FF-1001',
          skuName: '测试皮肤',
          matchMode: 'kuaishou_feifei_name',
        },
      },
    }),
    getProfileByKey: async (profileKey) => ({
      id: 10,
      profile_key: profileKey,
      name: 'kuaishou-feifei 履约',
      executor_key: profileKey,
      requires_claim: false,
      auto_dispatch: true,
    }),
  })

  assert.ok(plan)
  assert.equal(plan.executorKey, 'kuaishou_feifei')
  assert.equal(plan.requiresClaim, true)
  assert.equal(plan.autoDispatch, false)
  assert.equal(plan.context.kuaishouCloudFulfillment, null)
  assert.equal((plan.context.kuaishouFeifei as any).productCode, 'FF-1001')
  assert.equal((plan.context.kuaishouFeifei as any).productName, '测试皮肤')
})

test('planFulfillmentTaskForOrderItem 尊重履约路由选择 feifei', async () => {
  const plan = await planFulfillmentTaskForOrderItem({
    order: createOrder(),
    item: createOrderItem({
      sku_code: 'FF-ROUTE',
      sku_name: '同时命中商品',
      item_snapshot_json: {
        fulfillmentRoute: {
          selectedExecutorKey: 'kuaishou_feifei',
        },
        cloudtentacles: {
          cloudSourceKeys: ['account-a'],
          cloudSkuId: 74,
          cloudSkuName: 'Cloud 商品',
        },
        kuaishouFeifei: {
          productCode: 'FF-ROUTE',
          skuName: 'feifei 商品',
          matchMode: 'kuaishou_feifei_name',
        },
      },
    }),
    getProfileByKey: async (profileKey) => ({
      id: 10,
      profile_key: profileKey,
      name: '测试履约',
      executor_key: profileKey,
      requires_claim: false,
      auto_dispatch: true,
    }),
  })

  assert.ok(plan)
  assert.equal(plan.executorKey, 'kuaishou_feifei')
  assert.equal(plan.context.kuaishouCloudFulfillment, null)
  assert.equal((plan.context.kuaishouFeifei as any).productCode, 'FF-ROUTE')
})

test('planFulfillmentTaskForOrderItem 支持履约路由转人工', async () => {
  const plan = await planFulfillmentTaskForOrderItem({
    order: createOrder(),
    item: createOrderItem({
      sku_code: 'MANUAL-1',
      sku_name: '人工商品',
      item_snapshot_json: {
        fulfillmentRoute: {
          selectedExecutorKey: 'manual_dispatch',
        },
      },
    }),
    getProfileByKey: async (profileKey) => ({
      id: 1,
      profile_key: profileKey,
      name: '人工发货',
      executor_key: 'manual_dispatch',
      requires_claim: true,
      auto_dispatch: true,
    }),
  })

  assert.ok(plan)
  assert.equal(plan.executorKey, 'manual_dispatch')
  assert.equal(plan.requiresClaim, false)
  assert.equal(plan.autoDispatch, false)
  assert.equal(plan.context.kuaishouCloudFulfillment, null)
  assert.equal(plan.context.kuaishouFeifei, null)
})

test('planFulfillmentTaskForOrderItem 未命中平台配置时返回 null', async () => {
  const plan = await planFulfillmentTaskForOrderItem({
    order: createOrder(),
    item: createOrderItem({
      item_snapshot_json: {
        cloudtentacles: null,
        kuaishouFeifei: null,
      },
    }),
    getProfileByKey: async () => null,
  })

  assert.equal(plan, null)
})

function createOrder(patch: Partial<OrderRow> = {}): OrderRow {
  return {
    id: 1,
    provider: '91kaquan',
    platform: 'kuaishou',
    shop_id: '91kaquan',
    shop_name: '91卡券',
    platform_order_id: '2614900602069169',
    order_status: 'paid',
    pay_status: 'paid',
    buyer_id: '',
    buyer_name: '',
    receiver_contact: '',
    total_amount: 0,
    currency: 'CNY',
    raw_payload_json: '{}',
    paid_at: '2026-07-08T00:00:00.000Z',
    created_at: '2026-07-08T00:00:00.000Z',
    updated_at: '2026-07-08T00:00:00.000Z',
    ...patch,
  }
}

function createOrderItem(patch: Partial<OrderItemRow> = {}): OrderItemRow {
  return {
    id: 10,
    order_id: 1,
    sku_code: 'SKU-1',
    sku_name: '测试商品',
    quantity: 1,
    spec_json: '{}',
    item_snapshot_json: {},
    created_at: '2026-07-08T00:00:00.000Z',
    updated_at: '2026-07-08T00:00:00.000Z',
    ...patch,
  }
}
