/**
 * Built-in Viewport Commands
 *
 * Commands for viewport manipulation:
 * - fitToView: Fit all nodes in view
 * - fitSelection: Fit selected nodes in view
 * - resetViewport: Reset zoom and pan
 * - zoomIn: Zoom in
 * - zoomOut: Zoom out
 */

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

/**
 * Fit all nodes in view
 */
export const fitToViewCommand: CommandDefinition = {
	name: 'fitToView',
	description: 'Fit all nodes in the viewport',
	aliases: ['fit', 'fitAll'],
	category: 'viewport',
	inputs: [],
	execute: async (_inputs, ctx) => {
		ctx.layout.fitToBounds('graph');
	},
};

/**
 * Fit selected nodes in view
 */
export const fitSelectionCommand: CommandDefinition = {
	name: 'fitSelection',
	description: 'Fit selected nodes in the viewport',
	aliases: ['fitSel'],
	category: 'viewport',
	inputs: [],
	execute: async (_inputs, ctx) => {
		if (ctx.selectedNodeIds.size === 0) {
			throw new Error('No nodes selected');
		}
		ctx.layout.fitToBounds('selection');
	},
};

/**
 * Reset viewport to default
 */
export const resetViewportCommand: CommandDefinition = {
	name: 'resetViewport',
	description: 'Reset zoom and pan to default',
	aliases: ['reset', 'home'],
	category: 'viewport',
	inputs: [],
	execute: async (_inputs, ctx) => {
		const { resetViewportAtom } = await import('../../core/viewport-store');
		ctx.set(resetViewportAtom);
	},
};

/**
 * Zoom in
 */
export const zoomInCommand: CommandDefinition = {
	name: 'zoomIn',
	description: 'Zoom in on the canvas',
	aliases: ['+', 'in'],
	category: 'viewport',
	inputs: [],
	execute: async (_inputs, ctx) => {
		const { zoomAtom, setZoomAtom } = await import('../../core/viewport-store');
		const currentZoom = ctx.get(zoomAtom);
		ctx.set(setZoomAtom, { zoom: Math.min(5, currentZoom * 1.25) });
	},
};

/**
 * Zoom out
 */
export const zoomOutCommand: CommandDefinition = {
	name: 'zoomOut',
	description: 'Zoom out on the canvas',
	aliases: ['-', 'out'],
	category: 'viewport',
	inputs: [],
	execute: async (_inputs, ctx) => {
		const { zoomAtom, setZoomAtom } = await import('../../core/viewport-store');
		const currentZoom = ctx.get(zoomAtom);
		ctx.set(setZoomAtom, { zoom: Math.max(0.1, currentZoom / 1.25) });
	},
};

/**
 * Register all viewport commands
 */
export function registerViewportCommands(): void {
	registerCommand(fitToViewCommand);
	registerCommand(fitSelectionCommand);
	registerCommand(resetViewportCommand);
	registerCommand(zoomInCommand);
	registerCommand(zoomOutCommand);
}
