// Escaping contract of the GFM pipe-table builder (PR #348 review fix):
// user-generated free text (FA comments, action descriptions, plausibility
// explanations) flows into mdTable cells and may contain `|` or newlines —
// unescaped, either would corrupt the table grammar for every downstream
// KI-Chat consumer. These tests pin that contract so a refactor of
// mdTableCell cannot silently drop it.

import { describe, expect, it } from 'vitest'
import { mdTable } from '../internal/md-shared'

/** Pipes that act as column separators: `|` not preceded by a backslash. */
function structuralPipeCount(line: string): number {
  return (line.match(/(?<!\\)\|/g) ?? []).length
}

describe('mdTable — cell escaping', () => {
  it('escapes literal pipes in body and header cells so the column structure survives', () => {
    const md = mdTable(['Nr', 'Beschreibung | Detail'], [['1', 'Werkzeugwechsel | Rüstzeit reduzieren']])
    const lines = md.split('\n')
    expect(lines).toHaveLength(3)
    expect(lines[0]).toContain('Beschreibung \\| Detail')
    expect(lines[2]).toContain('Werkzeugwechsel \\| Rüstzeit reduzieren')
    // Every row still parses to exactly 2 columns → 3 structural pipes each.
    for (const line of lines) {
      expect({ line, pipes: structuralPipeCount(line) }).toEqual({ line, pipes: 3 })
    }
  })

  it('replaces embedded newlines (\\n and \\r\\n) with spaces — one table row stays one line', () => {
    const md = mdTable(['Feld'], [['Zeile eins\nZeile zwei'], ['CRLF eins\r\nCRLF zwei']])
    const lines = md.split('\n')
    expect(lines).toHaveLength(4) // header + separator + 2 body rows
    expect(lines[2]).toBe('| Zeile eins Zeile zwei |')
    expect(lines[3]).toBe('| CRLF eins CRLF zwei |')
  })

  it('handles the combined worst case (pipe + newline in the same cell)', () => {
    const md = mdTable(['Kommentar'], [['Prüfung offen | Nacharbeit\nsiehe Protokoll']])
    const lines = md.split('\n')
    expect(lines).toHaveLength(3)
    expect(lines[2]).toBe('| Prüfung offen \\| Nacharbeit siehe Protokoll |')
  })
})
