/**
 * Mutation queue for tracking pending node updates
 *
 * Prevents race conditions during rapid drag operations.
 */

import type { NodeId, NodePosition, Json } from '../core/types';

export interface PendingMutation {
	inFlight: boolean;
	queuedPosition: NodePosition | null;
	queuedUiProperties: { [key: string]: Json | undefined } | null;
	graphId: string | null;
}

/**
 * Global map to track pending mutations per node
 */
export const pendingNodeMutations = new Map<NodeId, PendingMutation>();

/**
 * Get or create pending mutation state for a node
 */
export function getPendingState(nodeId: NodeId): PendingMutation {
	let state = pendingNodeMutations.get(nodeId);
	if (!state) {
		state = {
			inFlight: false,
			queuedPosition: null,
			queuedUiProperties: null,
			graphId: null,
		};
		pendingNodeMutations.set(nodeId, state);
	}
	return state;
}

/**
 * Clear pending state for a node
 */
export function clearPendingState(nodeId: NodeId): void {
	pendingNodeMutations.delete(nodeId);
}

/**
 * Clear all pending mutation state (used on graph switch)
 */
export function clearAllPendingMutations(): void {
	pendingNodeMutations.clear();
}

/**
 * Check if any node has pending mutations
 */
export function hasPendingMutations(): boolean {
	for (const state of pendingNodeMutations.values()) {
		if (state.inFlight || state.queuedPosition !== null || state.queuedUiProperties !== null) {
			return true;
		}
	}
	return false;
}
