import { describe, expect, it } from 'vitest'
import type { KbxWmsScanCommand } from '@kbx/contracts'

function replayOrder(commands: KbxWmsScanCommand[]) {
  // Scanner commands are sequence-sensitive and must never be parallelized.
  return [...commands].sort((a, b) => a.occurredAt.localeCompare(b.occurredAt))
}

describe('WMS scanner retry contract', () => {
  it('preserves the same idempotency key across transport retry', () => {
    const command: KbxWmsScanCommand = {
      taskId: 'task-1',
      barcode: 'LOC-A-01',
      source: 'keyboard-wedge',
      idempotencyKey: 'task-1:abc',
      expectedVersion: 7,
      occurredAt: '2026-08-08T07:00:00Z',
    }
    const retried = { ...command }
    expect(retried.idempotencyKey).toBe(command.idempotencyKey)
  })

  it('replays sequential scans in occurrence order', () => {
    const make = (key: string, occurredAt: string): KbxWmsScanCommand => ({
      taskId: 'task-1', barcode: key, source: 'keyboard-wedge', idempotencyKey: key,
      expectedVersion: 7, occurredAt,
    })
    expect(replayOrder([
      make('B', '2026-08-08T07:00:02Z'),
      make('A', '2026-08-08T07:00:01Z'),
    ]).map(x => x.idempotencyKey)).toEqual(['A', 'B'])
  })
})
