import { describe, it, expect, beforeEach } from 'vitest';
import { createStore } from 'jotai';
import Graph from 'graphology';
import type { GraphNodeAttributes, GraphEdgeAttributes, DBGraphNode } from '../core/types';
import { graphAtom, graphOptions, currentGraphIdAtom } from '../core/graph-store';
import { addNodeToLocalGraphAtom } from '../core/graph-mutations';
import { addEdgeToLocalGraphAtom } from '../core/graph-mutations-edges';
import { nodeKeysAtom, edgeKeysAtom } from '../core/graph-derived';

function makeDbNode(id: string, x = 0, y = 0): DBGraphNode {
	return {
		id, graph_id: 'test-graph', label: `Node ${id}`, node_type: 'default',
		configuration: null, ui_properties: { x, y, width: 200, height: 100, size: 15, zIndex: 0 },
		data: null, created_at: '2024-01-01T00:00:00Z', updated_at: '2024-01-01T00:00:00Z',
	};
}

function makeDbEdge(id: string, source: string, target: string) {
	return {
		id, graph_id: 'test-graph', source_node_id: source, target_node_id: target,
		edge_type: 'default', filter_condition: null, ui_properties: null, data: null,
		created_at: '2024-01-01T00:00:00Z', updated_at: '2024-01-01T00:00:00Z',
	};
}

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

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

	it('nodeKeysAtom starts empty', () => {
		expect(store.get(nodeKeysAtom)).toEqual([]);
	});

	it('edgeKeysAtom starts empty', () => {
		expect(store.get(edgeKeysAtom)).toEqual([]);
	});

	it('nodeKeysAtom reflects added nodes', () => {
		store.set(addNodeToLocalGraphAtom, makeDbNode('n1'));
		store.set(addNodeToLocalGraphAtom, makeDbNode('n2'));
		expect(store.get(nodeKeysAtom)).toHaveLength(2);
	});

	it('edgeKeysAtom reflects added edges', () => {
		store.set(addNodeToLocalGraphAtom, makeDbNode('n1'));
		store.set(addNodeToLocalGraphAtom, makeDbNode('n2'));
		store.set(addEdgeToLocalGraphAtom, makeDbEdge('e1', 'n1', 'n2'));
		expect(store.get(edgeKeysAtom)).toHaveLength(1);
	});

	it('graph.getNodeAttributes returns attributes', () => {
		store.set(addNodeToLocalGraphAtom, makeDbNode('n1', 50, 75));
		const graph = store.get(graphAtom);
		const attrs = graph.getNodeAttributes('n1') as GraphNodeAttributes;
		expect(attrs.x).toBe(50);
		expect(attrs.y).toBe(75);
	});

	it('graph.hasNode returns false for missing node', () => {
		expect(store.get(graphAtom).hasNode('missing')).toBe(false);
	});
});
