import { describe, it, expect } from 'vitest'
import type { QAFRow } from '@/lib/qaf-parser'
import { computeRootCause, type RootCauseInput } from '../root-cause'
import { computeFieldDiff } from '../differ'

function fd(field: keyof QAFRow, alt: number | null, neu: number | null) {
  return computeFieldDiff(field, alt, neu)
}

const input: RootCauseInput = {
  partNumber: '7490365',
  steps: [
    { stepLabel: '1 Montage', matchStatus: 'safe_match', fieldDiffs: [fd('fk', 100, 130), fd('lohnkosten', 30, 33)] },
    { stepLabel: '2 Schweissen', matchStatus: 'safe_match', fieldDiffs: [fd('fk', 200, 500), fd('mss', 50, 60)] },
  ],
  newSteps: ['3 Pruefen'],
  removedSteps: [],
  structureChangeSteps: [],
  currencyChanged: false,
}

describe('computeRootCause', () => {
  it('ranks the biggest absolute cost driver first', () => {
    const r = computeRootCause(input)
    expect(r.topAbsoluteDrivers[0].stepLabel).toBe('2 Schweissen')
    expect(r.topAbsoluteDrivers[0].field).toBe('fk')
    expect(r.topAbsoluteDrivers[0].deltaAbsolute).toBe(300)
  })

  it('surfaces structure changes', () => {
    const r = computeRootCause(input)
    expect(r.structureChanges.new).toContain('3 Pruefen')
    expect(r.structureChanges.removed).toEqual([])
  })

  it('produces a non-empty management summary mentioning the part number', () => {
    const r = computeRootCause(input)
    expect(r.managementSummary.length).toBeGreaterThan(0)
    expect(r.managementSummary).toContain('7490365')
    // 2–4 sentences, no speculation markers
    const sentences = r.managementSummary.split(/(?<=\.)\s+/).filter(Boolean)
    expect(sentences.length).toBeGreaterThanOrEqual(1)
    expect(sentences.length).toBeLessThanOrEqual(5)
  })

  it('flags currency effect when present', () => {
    const r = computeRootCause({ ...input, currencyChanged: true })
    expect(r.currencyEffect).toBe(true)
    expect(r.managementSummary.toLowerCase()).toContain('währung')
  })

  it('sets requiresReviewNote when structure changes need review', () => {
    const r = computeRootCause({ ...input, structureChangeSteps: ['2 Schweissen'] })
    expect(r.requiresReviewNote).toBe(true)
  })

  it('handles an empty comparison without throwing', () => {
    const r = computeRootCause({
      partNumber: null,
      steps: [],
      newSteps: [],
      removedSteps: [],
      structureChangeSteps: [],
      currencyChanged: false,
    })
    expect(r.topAbsoluteDrivers).toEqual([])
    expect(r.managementSummary.length).toBeGreaterThan(0)
  })
})
