import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { exportToCSV } from './exportUtils';

const fakeHref = 'blob://test-export';
let createdBlob = null;

describe('exportToCSV', () => {
  beforeEach(() => {
    vi.stubGlobal('URL', {
      createObjectURL: vi.fn((blob) => {
        createdBlob = blob;
        return fakeHref;
      }),
      revokeObjectURL: vi.fn(),
    });
    document.body.innerHTML = '';
  });

  afterEach(() => {
    vi.restoreAllMocks();
    createdBlob = null;
  });

  it('generates semicolon-delimited CSV with a UTF-8 BOM and correct headers', async () => {
    const data = [{
      annotationId: 'ann-1',
      modelId: 'model-1',
      annotator: 'Test User',
      fileHash: 'filehash',
      lastUpdated: '2026-04-26T12:00:00.000Z',
      atlasNameCs: 'Atlas CS',
      isChecked: true,
      checkerName: 'Checker',
      values: { 'trait-1': 'Value 1' }
    }];

    const schema = [{
      atlas_id: 'atlas-1',
      znaky: [
        {
          id: 'trait-1',
          label_cs: 'Trait 1',
          label_en: 'Trait 1',
          options: []
        }
      ]
    }];

    exportToCSV(data, (key) => key, 'cs', 'export.csv', ['trait-1'], schema);

    expect(URL.createObjectURL).toHaveBeenCalled();
    expect(createdBlob).toBeTruthy();

    const text = await createdBlob.text();
    expect(text.startsWith('\uFEFF')).toBe(true);
    expect(text).toContain('headerAnnotationId;headerModelId;headerAnnotator;headerFileHash;headerSaveDate;headerAtlas;headerCheckedBy;Trait 1');
    expect(text).toContain('"ann-1";"model-1";"Test User";"filehash"');
    expect(text).toContain('"Checker";"Value 1"');
  });
});
