import { describe, it, expect } from 'vitest';
import { historyToScript, generateShareUrl } from '../../src/utils/scriptTypes';
import type { FilterRecord, MeshLabWebScript } from '../../src/utils/scriptTypes';

describe('Script format', () => {
  it('generates script from history', () => {
    const history: FilterRecord[] = [
      { id: 'remove_duplicate_vertices', name: 'Remove Dup', params: {}, timestamp: 0 },
      { id: 'laplacian_smooth', name: 'Smooth', params: { iterations: 3 }, timestamp: 1 },
    ];
    const script = historyToScript(history, 'Test Script');
    expect(script.version).toBe(1);
    expect(script.filters.length).toBe(2);
    expect(script.filters[1].params.iterations).toBe(3);
  });

  it('JSON round-trip preserves data', () => {
    const script: MeshLabWebScript = {
      version: 1, name: 'Test', createdAt: '', filters: [
        { id: 'laplacian_smooth', params: { iterations: 5 } },
      ],
    };
    const loaded = JSON.parse(JSON.stringify(script)) as MeshLabWebScript;
    expect(loaded.filters[0].params.iterations).toBe(5);
  });
});

describe('Share URL', () => {
  it('encodes and decodes script', () => {
    const script: MeshLabWebScript = {
      version: 1, name: 'Test', createdAt: '', filters: [
        { id: 'laplacian_smooth', params: { iterations: 3 } },
      ],
    };
    const url = generateShareUrl(script);
    expect(url).toContain('?script=');

    // Extract the base64 part manually (since URL may not have full origin in Node)
    const scriptParam = url.split('?script=')[1];
    const decoded = JSON.parse(decodeURIComponent(escape(atob(scriptParam))));
    expect(decoded.filters[0].params.iterations).toBe(3);
  });
});
