import { describe, expect, it } from 'vitest'
import { isKbxBarcodeDuplicate, normalizeKbxBarcode } from '@kbx/ui'

describe('KbxBarcodeCapture contract', () => {
  it('normalizes scanner text but never invents another barcode', () => {
    expect(normalizeKbxBarcode(' 8801234567890 ', 'keyboard-wedge', 3, 256, 1)).toEqual({
      rawValue: ' 8801234567890 ',
      normalizedValue: '8801234567890',
      source: 'keyboard-wedge',
      occurredAt: 1,
    })
  })

  it('rejects implausibly short and oversized scanner buffers', () => {
    expect(normalizeKbxBarcode('A', 'keyboard-wedge', 3, 256, 1)).toBeNull()
    expect(normalizeKbxBarcode('123456', 'keyboard-wedge', 3, 5, 1)).toBeNull()
  })

  it('ignores only the same barcode inside the short device debounce window', () => {
    const last=normalizeKbxBarcode('ABC001','keyboard-wedge',3,256,1000)!
    const duplicate=normalizeKbxBarcode('ABC001','keyboard-wedge',3,256,1100)!
    const legitimateLaterScan=normalizeKbxBarcode('ABC001','keyboard-wedge',3,256,1400)!
    expect(isKbxBarcodeDuplicate(duplicate,last,180)).toBe(true)
    expect(isKbxBarcodeDuplicate(legitimateLaterScan,last,180)).toBe(false)
  })
})
