// Tests for the shared KAR-927 adversarial-review fix (F1/F2/F3) helper —
// the cheap, bounded header-region scan material-parser.ts's
// parseMaterialSheet and sbm-parser.ts's parseSbmSheet both use to classify
// name-matching candidate sheets without a full worksheetToGrid parse.

import { describe, it, expect } from 'vitest'
import ExcelJS from 'exceljs'
import {
  normalizeIgnoredCandidateSheets,
  worksheetHasHeaderLabelInRegion,
  CANDIDATE_SCAN_MAX_COLS,
  type IgnoredCandidateSheetEntry,
} from '../candidate-sheet-plausibility'

describe('normalizeIgnoredCandidateSheets', () => {
  it('undefined -> []', () => {
    expect(normalizeIgnoredCandidateSheets(undefined)).toEqual([])
  })

  it('empty array -> []', () => {
    expect(normalizeIgnoredCandidateSheets([])).toEqual([])
  })

  it('current-shape entries pass through unchanged', () => {
    const entries: IgnoredCandidateSheetEntry[] = [
      { name: 'SBM_Matrix', plausibleData: false },
      { name: 'SBM-DEVICES-FWZ (EN)', plausibleData: true }, // allow-customer-string
    ]
    expect(normalizeIgnoredCandidateSheets(entries)).toEqual(entries)
  })

  it('legacy string[] entries map to plausibleData: true (old strict-gate guarantee preserved)', () => {
    expect(normalizeIgnoredCandidateSheets(['Material '])).toEqual([{ name: 'Material ', plausibleData: true }])
  })

  it('tolerates a mixed legacy/current array (defensive — should never occur in practice)', () => {
    expect(normalizeIgnoredCandidateSheets(['Legacy Sheet', { name: 'New Sheet', plausibleData: false }])).toEqual([
      { name: 'Legacy Sheet', plausibleData: true },
      { name: 'New Sheet', plausibleData: false },
    ])
  })
})

describe('worksheetHasHeaderLabelInRegion', () => {
  function sheetWithRows(rows: unknown[][]): ExcelJS.Worksheet {
    const wb = new ExcelJS.Workbook()
    const ws = wb.addWorksheet('Test')
    rows.forEach((row, i) => {
      ws.getRow(i + 1).values = row as ExcelJS.CellValue[]
    })
    return ws
  }

  it('finds a label within the bounded row/col window', () => {
    const ws = sheetWithRows([['foo', 'Benennung Rohmaterial / Kaufteil', 'bar']])
    const found = worksheetHasHeaderLabelInRegion(
      ws,
      20,
      CANDIDATE_SCAN_MAX_COLS,
      (cell) => cell === 'Benennung Rohmaterial / Kaufteil',
    )
    expect(found).toBe(true)
  })

  it('returns false when the label is not present anywhere in the scanned region', () => {
    const ws = sheetWithRows([['foo', 'bar', 'baz']])
    const found = worksheetHasHeaderLabelInRegion(ws, 20, CANDIDATE_SCAN_MAX_COLS, (cell) => cell === 'Werkzeugart')
    expect(found).toBe(false)
  })

  it('does not find a label beyond the row limit (bounded scan, not a full-sheet walk)', () => {
    const rows: unknown[][] = []
    for (let i = 0; i < 25; i++) rows.push(['filler'])
    rows.push(['Werkzeug-/ Vorrichtungsart'])
    const ws = sheetWithRows(rows)
    const found = worksheetHasHeaderLabelInRegion(ws, 20, CANDIDATE_SCAN_MAX_COLS, (cell) => cell === 'Werkzeug-/ Vorrichtungsart')
    expect(found).toBe(false)
  })

  it('does not find a label beyond the column limit (bounded scan, not a full-row walk)', () => {
    const row: unknown[] = new Array(CANDIDATE_SCAN_MAX_COLS + 5).fill('filler')
    row[CANDIDATE_SCAN_MAX_COLS + 2] = 'Werkzeug-/ Vorrichtungsart'
    const ws = sheetWithRows([row])
    const found = worksheetHasHeaderLabelInRegion(ws, 20, CANDIDATE_SCAN_MAX_COLS, (cell) => cell === 'Werkzeug-/ Vorrichtungsart')
    expect(found).toBe(false)
  })

  it('never throws — a worksheet whose getRow() throws resolves to false (F3)', () => {
    const hostileWs = {
      getRow: () => {
        throw new Error('simulated parser-hostile worksheet')
      },
    } as unknown as ExcelJS.Worksheet
    expect(() => worksheetHasHeaderLabelInRegion(hostileWs, 20, CANDIDATE_SCAN_MAX_COLS, () => true)).not.toThrow()
    expect(worksheetHasHeaderLabelInRegion(hostileWs, 20, CANDIDATE_SCAN_MAX_COLS, () => true)).toBe(false)
  })

  it('empty header cells never match (isIdentityLabel never called with "")', () => {
    const ws = sheetWithRows([['', '', '']])
    const found = worksheetHasHeaderLabelInRegion(ws, 20, CANDIDATE_SCAN_MAX_COLS, (cell) => cell === '')
    expect(found).toBe(false)
  })
})
