import { describe, it, expect, beforeEach } from 'vitest';
import { createStore } from 'jotai';
import Graph from 'graphology';
import type { GraphNodeAttributes, GraphEdgeAttributes } from '../core/types';
import { graphAtom, graphOptions } from '../core/graph-store';
import {
	historyStateAtom,
	canUndoAtom,
	canRedoAtom,
	undoCountAtom,
	redoCountAtom,
	pushHistoryAtom,
	undoAtom,
	redoAtom,
	clearHistoryAtom,
	historyLabelsAtom,
} from '../core/history-store';

describe('useCanvasHistory (atom-level)', () => {
	let store: ReturnType<typeof createStore>;

	beforeEach(() => {
		store = createStore();
		store.set(graphAtom, new Graph<GraphNodeAttributes, GraphEdgeAttributes>(graphOptions));
	});

	it('starts with canUndo=false, canRedo=false', () => {
		expect(store.get(canUndoAtom)).toBe(false);
		expect(store.get(canRedoAtom)).toBe(false);
	});

	it('recordSnapshot (pushHistoryAtom) makes canUndo true', () => {
		store.set(pushHistoryAtom, 'Test');
		expect(store.get(canUndoAtom)).toBe(true);
		expect(store.get(undoCountAtom)).toBe(1);
	});

	it('undo moves entry to future', () => {
		store.set(pushHistoryAtom, 'Step');
		store.set(undoAtom);
		expect(store.get(canUndoAtom)).toBe(false);
		expect(store.get(canRedoAtom)).toBe(true);
	});

	it('redo moves entry back to past', () => {
		store.set(pushHistoryAtom, 'Step');
		store.set(undoAtom);
		store.set(redoAtom);
		expect(store.get(undoCountAtom)).toBe(1);
		expect(store.get(redoCountAtom)).toBe(0);
	});

	it('clear resets all history', () => {
		store.set(pushHistoryAtom, 'A');
		store.set(pushHistoryAtom, 'B');
		store.set(clearHistoryAtom);
		expect(store.get(canUndoAtom)).toBe(false);
		expect(store.get(canRedoAtom)).toBe(false);
	});

	it('historyLabels returns labels', () => {
		store.set(pushHistoryAtom, 'Alpha');
		store.set(pushHistoryAtom, 'Beta');
		const labels = store.get(historyLabelsAtom);
		expect(labels.past).toEqual(['Alpha', 'Beta']);
	});
});
