import { describe, it, expect } from 'vitest'
import {
  isObservation,
  isMeasure,
  promoteToMeasure,
  filterByType,
  type LscEntry,
  type LscEntryType,
} from '@/lib/lsc-workshop/observations'

function makeEntry(overrides: Partial<LscEntry> = {}): LscEntry {
  return {
    id: 'x',
    project_id: 'p',
    title: 't',
    type: 'beobachtung',
    status: 'offen',
    priority: 'mittel',
    effort_level: null,
    benefit_level: null,
    matrix_x: null,
    matrix_y: null,
    ...overrides,
  }
}

describe('isObservation / isMeasure', () => {
  it('distinguishes observation from measure by type field', () => {
    const obs = makeEntry({ type: 'beobachtung' })
    const m = makeEntry({ type: 'massnahme' })
    expect(isObservation(obs)).toBe(true)
    expect(isObservation(m)).toBe(false)
    expect(isMeasure(m)).toBe(true)
    expect(isMeasure(obs)).toBe(false)
  })
})

describe('promoteToMeasure', () => {
  it('changes type to massnahme', () => {
    const obs = makeEntry({ type: 'beobachtung' })
    const promoted = promoteToMeasure(obs)
    expect(promoted.type).toBe('massnahme')
  })

  it('keeps all other fields unchanged', () => {
    const obs = makeEntry({ title: 'Wartezeit zu lang', priority: 'hoch', effort_level: 3 })
    const promoted = promoteToMeasure(obs)
    expect(promoted.title).toBe('Wartezeit zu lang')
    expect(promoted.priority).toBe('hoch')
    expect(promoted.effort_level).toBe(3)
  })

  it('is idempotent on existing massnahme', () => {
    const m = makeEntry({ type: 'massnahme' })
    const promoted = promoteToMeasure(m)
    expect(promoted.type).toBe('massnahme')
  })
})

describe('filterByType', () => {
  const data: LscEntry[] = [
    makeEntry({ id: 'a', type: 'beobachtung' }),
    makeEntry({ id: 'b', type: 'massnahme' }),
    makeEntry({ id: 'c', type: 'beobachtung' }),
    makeEntry({ id: 'd', type: 'massnahme' }),
  ]

  it('returns all when filter is "alle"', () => {
    expect(filterByType(data, 'alle')).toHaveLength(4)
  })

  it('returns only observations when filter is "beobachtung"', () => {
    const filtered = filterByType(data, 'beobachtung')
    expect(filtered).toHaveLength(2)
    expect(filtered.every((e) => e.type === 'beobachtung')).toBe(true)
  })

  it('returns only measures when filter is "massnahme"', () => {
    const filtered = filterByType(data, 'massnahme')
    expect(filtered).toHaveLength(2)
    expect(filtered.every((e) => e.type === 'massnahme')).toBe(true)
  })

  it('preserves order', () => {
    const filtered: LscEntryType[] = ['beobachtung']
    expect(filterByType(data, 'beobachtung').map((e) => e.id)).toEqual(['a', 'c'])
    expect(filtered.length).toBe(1)
  })
})
