import { describe, expect, test } from 'vitest';
import { CURRENT_DATASET_VERSION } from '@core/dataset';
import { migrateDataset } from './dataset-migrations';

describe('migrateDataset', () => {
  test('stamps the current version and fills missing fields with defaults', () => {
    const d = migrateDataset({ id: 7, data: 'a,b\n1,2', format: 'csv', source: 'inline' });

    expect(d.id).toBe(7);
    expect(d.version).toBe(CURRENT_DATASET_VERSION);
    expect(d.name).toBe('Untitled');
    expect(d.comment).toBe('');
    expect(d.columns).toEqual([]);
    expect(d.columnStats).toEqual([]);
  });

  test('an inline record carries no url/fetchedAt keys', () => {
    const d = migrateDataset({ id: 1, data: [{ a: 1 }], format: 'json', source: 'inline' });
    expect(d.source).toBe('inline');
    expect('url' in d).toBe(false);
    expect('fetchedAt' in d).toBe(false);
  });

  test('v1→v2: a legacy URL record moves its address out of data into url', () => {
    // Pre-v2 shape: the URL lived in `data`, there was no `url`/`fetchedAt`, and the
    // profile was N/A. It becomes an unfetched reference: url set, data cleared.
    const d = migrateDataset({
      id: 2,
      data: 'https://example.com/data.csv',
      format: 'csv',
      source: 'url',
      rowCount: null,
      columns: [],
    });

    expect(d.version).toBe(CURRENT_DATASET_VERSION);
    expect(d.source).toBe('url');
    expect(d.url).toBe('https://example.com/data.csv');
    expect(d.data).toBeNull();
    expect(d.fetchedAt).toBeNull();
    expect(d.rowCount).toBeNull();
  });

  test('a v2 URL snapshot is preserved (data, url, and fetchedAt all kept)', () => {
    const d = migrateDataset({
      id: 3,
      version: 2,
      data: 'a,b\n1,2',
      url: 'https://example.com/data.csv',
      fetchedAt: '2026-06-10T00:00:00.000Z',
      format: 'csv',
      source: 'url',
      rowCount: 1,
      columns: ['a', 'b'],
    });

    expect(d.data).toBe('a,b\n1,2');
    expect(d.url).toBe('https://example.com/data.csv');
    expect(d.fetchedAt).toBe('2026-06-10T00:00:00.000Z');
    expect(d.rowCount).toBe(1);
  });

  test('preserves unknown fields so a newer build round-trips without loss', () => {
    const d = migrateDataset({
      id: 1,
      data: [],
      format: 'json',
      source: 'inline',
      futureField: 42,
    });
    expect((d as unknown as Record<string, unknown>).futureField).toBe(42);
  });
});
