import { describe, expect, it } from 'vitest';

import { createTinyflowDataSync } from './dataSync';

describe('createTinyflowDataSync', () => {
  it('克隆真正的外部数据并跳过相同内容', () => {
    const sync = createTinyflowDataSync();
    const data = {
      edges: [],
      nodes: [{ data: { title: '开始' }, id: 'start', position: { x: 0, y: 0 } }],
    };

    const cloned = sync.cloneExternalDataIfChanged(data);

    expect(cloned).toEqual(data);
    expect(cloned).not.toBe(data);
    expect(sync.cloneExternalDataIfChanged(data)).toBeNull();
  });

  it('跳过原生画布回传后由父组件形成的属性回声', () => {
    const sync = createTinyflowDataSync();
    const emitted = {
      edges: [],
      nodes: [{ data: { title: '开始' }, id: 'start', position: { x: 12, y: 8 } }],
      viewport: { x: 20, y: 30, zoom: 1 },
    };

    sync.markNativeData(emitted);

    expect(
      sync.cloneExternalDataIfChanged(structuredClone(emitted)),
    ).toBeNull();
  });

  it('原生回传后仍应用内容不同的外部更新', () => {
    const sync = createTinyflowDataSync();
    const emitted = {
      edges: [],
      nodes: [{ data: { title: '开始' }, id: 'start', position: { x: 12, y: 8 } }],
    };
    sync.markNativeData(emitted);

    const external = {
      ...emitted,
      nodes: [
        {
          ...emitted.nodes[0],
          data: { title: '已更新' },
        },
      ],
    };

    expect(sync.cloneExternalDataIfChanged(external)).toEqual(external);
  });

  it('画布变化后允许重新应用曾经加载过的外部版本', () => {
    const sync = createTinyflowDataSync();
    const initial = {
      edges: [],
      nodes: [{ data: { title: '初始' }, id: 'start', position: { x: 0, y: 0 } }],
    };
    expect(sync.cloneExternalDataIfChanged(initial)).toEqual(initial);

    sync.markNativeData({
      ...initial,
      nodes: [
        {
          ...initial.nodes[0],
          position: { x: 120, y: 80 },
        },
      ],
    });

    expect(sync.cloneExternalDataIfChanged(initial)).toEqual(initial);
  });
});
