import { toCsv } from './toCsv';

describe('toCsv', () => {
  const headers = [
    { key: 'id', label: 'ID' },
    { key: 'name', label: 'Name' },
  ];

  it('serializes a header row + one row per item', () => {
    const csv = toCsv(
      [
        { id: 1, name: 'Alice' },
        { id: 2, name: 'Bob' },
      ],
      headers,
    );
    expect(csv).toBe('ID,Name\r\n1,Alice\r\n2,Bob');
  });

  it('quotes a field containing a comma', () => {
    const csv = toCsv([{ id: 1, name: 'Doe, Jane' }], headers);
    expect(csv).toBe('ID,Name\r\n1,"Doe, Jane"');
  });

  it('quotes a field containing an embedded quote, doubling it', () => {
    const csv = toCsv([{ id: 1, name: 'Say "hi"' }], headers);
    expect(csv).toBe('ID,Name\r\n1,"Say ""hi"""');
  });

  it('uses CRLF line endings throughout', () => {
    const csv = toCsv(
      [
        { id: 1, name: 'Alice' },
        { id: 2, name: 'Bob' },
      ],
      headers,
    );
    expect(csv.split('\r\n')).toHaveLength(3);
    expect(csv).not.toMatch(/(?<!\r)\n/);
  });

  it('renders an empty rows list as just the header row', () => {
    expect(toCsv([], headers)).toBe('ID,Name');
  });
});
