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

import { resolveOrderItemSyncPlan } from './order-item-repo.js'

test('resolveOrderItemSyncPlan preserves matching order item ids across repeated source syncs', () => {
  const existingItems = [
    {
      id: 15,
      sku_code: 'sku-a',
      sku_name: '礼包 A',
      quantity: 1,
    },
  ]
  const nextItems = [
    {
      skuCode: 'sku-a',
      skuName: '礼包 A',
      quantity: 1,
      specJson: '{}',
      itemSnapshotJson: '{}',
      createdAt: '2026-04-14T12:00:00.000Z',
      updatedAt: '2026-04-14T12:00:00.000Z',
    },
  ]

  const plan = resolveOrderItemSyncPlan(existingItems, nextItems)

  assert.deepEqual(plan.updates, [
    {
      orderItemId: 15,
      item: nextItems[0],
    },
  ])
  assert.deepEqual(plan.creates, [])
  assert.deepEqual(plan.deletes, [])
})

test('resolveOrderItemSyncPlan matches by identity before falling back to position', () => {
  const existingItems = [
    { id: 21, sku_code: 'sku-a', sku_name: '礼包 A', quantity: 1 },
    { id: 22, sku_code: 'sku-b', sku_name: '礼包 B', quantity: 1 },
  ]
  const nextItems = [
    {
      skuCode: 'sku-b',
      skuName: '礼包 B',
      quantity: 1,
      specJson: '{}',
      itemSnapshotJson: '{}',
      createdAt: '2026-04-14T12:00:00.000Z',
      updatedAt: '2026-04-14T12:00:00.000Z',
    },
    {
      skuCode: 'sku-a',
      skuName: '礼包 A',
      quantity: 1,
      specJson: '{}',
      itemSnapshotJson: '{}',
      createdAt: '2026-04-14T12:00:00.000Z',
      updatedAt: '2026-04-14T12:00:00.000Z',
    },
  ]

  const plan = resolveOrderItemSyncPlan(existingItems, nextItems)

  assert.deepEqual(
    plan.updates.map((item) => item.orderItemId),
    [22, 21],
  )
  assert.deepEqual(plan.creates, [])
  assert.deepEqual(plan.deletes, [])
})

test('resolveOrderItemSyncPlan keeps surplus existing ids for conditional cleanup instead of recreating everything', () => {
  const existingItems = [
    { id: 31, sku_code: 'sku-a', sku_name: '礼包 A', quantity: 1 },
    { id: 32, sku_code: 'sku-b', sku_name: '礼包 B', quantity: 1 },
  ]
  const nextItems = [
    {
      skuCode: 'sku-a',
      skuName: '礼包 A',
      quantity: 1,
      specJson: '{}',
      itemSnapshotJson: '{}',
      createdAt: '2026-04-14T12:00:00.000Z',
      updatedAt: '2026-04-14T12:00:00.000Z',
    },
  ]

  const plan = resolveOrderItemSyncPlan(existingItems, nextItems)

  assert.deepEqual(
    plan.updates.map((item) => item.orderItemId),
    [31],
  )
  assert.deepEqual(plan.creates, [])
  assert.deepEqual(plan.deletes, [32])
})
