import assert from 'node:assert/strict';
import test from 'node:test';
import {
  commitLayoutDrawHistory,
  createLayoutDrawHistoryState,
  redoLayoutDrawHistory,
  undoLayoutDrawHistory,
} from '../../src/features/layout/draw/layoutDrawHistory.ts';
import type { LayoutDrawDocument } from '../../src/features/layout/draw/layoutDrawTypes.ts';

function createDocument(partial?: Partial<LayoutDrawDocument>): LayoutDrawDocument {
  return {
    backgroundMode: partial?.backgroundMode ?? 'grid',
    shapes:
      partial?.shapes ?? [
        {
          id: 'line-1',
          type: 'line',
          x1: 10,
          y1: 20,
          x2: 10,
          y2: 180,
          orientation: 'vertical',
          label: '',
        },
      ],
  };
}

test('commits a new snapshot into undo history and clears redo history', () => {
  const initial = createLayoutDrawHistoryState(createDocument({ shapes: [] }));
  const committed = commitLayoutDrawHistory(initial, createDocument());

  assert.equal(committed.past.length, 1);
  assert.equal(committed.future.length, 0);
  assert.equal(committed.present.shapes.length, 1);
});

test('undo restores the previous snapshot and redo reapplies it', () => {
  const initial = createLayoutDrawHistoryState(createDocument({ shapes: [] }));
  const committed = commitLayoutDrawHistory(initial, createDocument());
  const undone = undoLayoutDrawHistory(committed);
  const redone = redoLayoutDrawHistory(undone);

  assert.equal(undone.present.shapes.length, 0);
  assert.equal(redone.present.shapes.length, 1);
});

test('does not create duplicate history entries for unchanged documents', () => {
  const initialDocument = createDocument();
  const initial = createLayoutDrawHistoryState(initialDocument);
  const committed = commitLayoutDrawHistory(initial, initialDocument);

  assert.equal(committed, initial);
  assert.equal(committed.past.length, 0);
});
