import {
  buildExportFilename,
  extractMarkdownTables,
  parseMarkdownBlocks,
  sanitizeFilenamePart,
  stripMarkdown,
} from './markdownUtils';
import { selectTabularStrategy } from './exportChat';

describe('export markdown utils', () => {
  it('sanitises filenames with title + ISO date', () => {
    expect(sanitizeFilenamePart('Hesychia Taylor Swift Question!')).toBe(
      'hesychia-taylor-swift-question',
    );
    expect(
      buildExportFilename('Hesychia Taylor Swift Question', 'pdf', new Date('2026-08-02T12:00:00Z')),
    ).toBe('hesychia-taylor-swift-question-2026-08-02.pdf');
  });

  it('strips markdown for plain text', () => {
    expect(stripMarkdown('# Hello\n\n**world**')).toContain('Hello');
    expect(stripMarkdown('# Hello\n\n**world**')).not.toContain('**');
  });

  it('parses headings, lists, tables, and code', () => {
    const blocks = parseMarkdownBlocks(
      [
        '# Title',
        '',
        '- a',
        '- b',
        '',
        '```js',
        'console.log(1)',
        '```',
        '',
        '| A | B |',
        '| --- | --- |',
        '| 1 | 2 |',
      ].join('\n'),
    );
    expect(blocks.find((b) => b.type === 'heading')).toMatchObject({
      level: 1,
      text: 'Title',
    });
    expect(blocks.find((b) => b.type === 'list')).toMatchObject({
      ordered: false,
      items: ['a', 'b'],
    });
    expect(blocks.find((b) => b.type === 'code')).toMatchObject({
      language: 'js',
      text: 'console.log(1)',
    });
    expect(blocks.find((b) => b.type === 'table')).toMatchObject({
      headers: ['A', 'B'],
      rows: [['1', '2']],
    });
  });

  it('selects tabular strategy per CSV/XLSX rules', () => {
    const withTable = '| A | B |\n| --- | --- |\n| 1 | 2 |';
    expect(selectTabularStrategy('message', withTable)).toBe('tables');
    expect(selectTabularStrategy('message', 'no table here')).toBe('turns');
    expect(selectTabularStrategy('conversation', withTable)).toBe('turns');
    expect(extractMarkdownTables(withTable)).toHaveLength(1);
  });
});
