/**
 * Built-in Merge Commands
 *
 * Commands for merging multiple nodes into one.
 * Edges from doomed nodes are re-routed to the survivor.
 */

import type { CommandDefinition } from '../types';
import { registerCommand } from '../registry';

/**
 * Merge selected nodes into one (first selected survives)
 */
export const mergeNodesCommand: CommandDefinition = {
	name: 'mergeNodes',
	description: 'Merge selected nodes into one (first selected survives)',
	aliases: ['merge'],
	category: 'nodes',
	inputs: [],
	execute: async (_inputs, ctx) => {
		if (ctx.selectedNodeIds.size < 2) return;

		const { mergeNodesAtom } = await import('../../core/graph-mutations');
		const { clearSelectionAtom, addNodesToSelectionAtom } = await import('../../core/selection-store');

		const nodeIds = Array.from(ctx.selectedNodeIds);
		ctx.set(mergeNodesAtom, { nodeIds });
		ctx.set(clearSelectionAtom);
		ctx.set(addNodesToSelectionAtom, [nodeIds[0]]);
	},
};

/**
 * Register all merge commands
 */
export function registerMergeCommands(): void {
	registerCommand(mergeNodesCommand);
}
