import { describe, it, expect } from 'vitest'
import { selectBaseline, type QafFileRef } from '../baseline'

function f(id: string, quotationDate: string | null, uploadedAt?: string): QafFileRef {
  return { id, fileName: `${id}.xlsx`, quotationDate, uploadedAt }
}

describe('selectBaseline', () => {
  it('needs at least two files', () => {
    const r = selectBaseline([f('a', '2024-01-01')])
    expect(r.status).toBe('insufficient')
    expect(r.altId).toBeNull()
    expect(r.neuId).toBeNull()
  })

  it('two distinct dates → oldest is ALT, newest is NEU', () => {
    const r = selectBaseline([f('new', '2025-04-29'), f('old', '2023-12-18')])
    expect(r.status).toBe('ok')
    expect(r.altId).toBe('old')
    expect(r.neuId).toBe('new')
  })

  it('more than two → oldest vs newest', () => {
    const r = selectBaseline([f('a', '2023-01-01'), f('b', '2024-06-01'), f('c', '2025-02-01')])
    expect(r.altId).toBe('a')
    expect(r.neuId).toBe('c')
    expect(r.status).toBe('ok')
  })

  it('missing quotation date → baseline_review but still proposes via upload order', () => {
    const r = selectBaseline([f('a', null, '2024-01-01T00:00:00Z'), f('b', null, '2024-05-01T00:00:00Z')])
    expect(r.status).toBe('baseline_review')
    expect(r.altId).toBe('a')
    expect(r.neuId).toBe('b')
  })

  it('identical quotation dates → baseline_review', () => {
    const r = selectBaseline([f('a', '2024-01-01', '2024-02-01T00:00:00Z'), f('b', '2024-01-01', '2024-03-01T00:00:00Z')])
    expect(r.status).toBe('baseline_review')
    // still proposes a deterministic order (upload time)
    expect(r.altId).toBe('a')
    expect(r.neuId).toBe('b')
  })

  it('manual selection overrides and is ok', () => {
    const r = selectBaseline([f('a', '2023-01-01'), f('b', '2024-01-01'), f('c', '2025-01-01')], {
      mode: 'manual',
      manualAltId: 'c',
      manualNeuId: 'a',
    })
    expect(r.status).toBe('ok')
    expect(r.altId).toBe('c')
    expect(r.neuId).toBe('a')
  })

  it('manual with unknown id falls back to baseline_review', () => {
    const r = selectBaseline([f('a', '2023-01-01'), f('b', '2024-01-01')], {
      mode: 'manual',
      manualAltId: 'x',
      manualNeuId: 'a',
    })
    expect(r.status).toBe('baseline_review')
  })
})
