import { describe, expect, test } from 'vitest';
import { CURRENT_SNIPPET_VERSION } from '@core/snippet';
import { migrateSnippet } from './snippet-migrations';

describe('migrateSnippet', () => {
  test('stamps the current version and fills missing fields with defaults', () => {
    const s = migrateSnippet({ id: 7, spec: '{"mark":"bar"}' });

    expect(s.id).toBe('7');
    expect(s.version).toBe(CURRENT_SNIPPET_VERSION);
    expect(s.name).toBe('Untitled');
    expect(s.draftSpec).toBe('{"mark":"bar"}'); // defaults to published spec
    expect(s.comment).toBe('');
    expect(s.tags).toEqual([]);
    expect(s.datasetRefs).toEqual([]);
    expect(s.meta).toEqual({});
  });

  test('coerces an object-form spec into canonical JSON text', () => {
    const s = migrateSnippet({ id: 'a', spec: { mark: 'point' } });
    expect(s.spec).toBe(JSON.stringify({ mark: 'point' }, null, 2));
  });

  test('preserves unknown fields so a newer build round-trips without loss', () => {
    const s = migrateSnippet({ id: 'a', spec: '{}', futureField: 42 });
    expect((s as unknown as Record<string, unknown>).futureField).toBe(42);
  });

  test('keeps a distinct draftSpec when present', () => {
    const s = migrateSnippet({ id: 'a', spec: '{"a":1}', draftSpec: '{"a":2}' });
    expect(s.spec).toBe('{"a":1}');
    expect(s.draftSpec).toBe('{"a":2}');
  });
});
