/**
 * Base Command - Abstract Command Class
 * All CLI commands extend this class
 */
import { ErrorHandler } from './ErrorHandler.js';
import { ErrorFactory } from '../exceptions/ZintrustError.js';
import { Command } from 'commander';
/**
 * Command Factory Helper
 * Sealed namespace for immutability
 */
export const BaseCommand = Object.freeze({
    /**
     * Create a command instance with common logic
     */
    create(config) {
        const getCommand = () => {
            const command = new Command(config.name);
            command.description(config.description);
            command.option('--verbose', 'Enable verbose output');
            if (typeof config.aliases === 'string' && config.aliases.length > 0) {
                command.alias(config.aliases);
            }
            if (Array.isArray(config.aliases)) {
                for (const alias of config.aliases) {
                    if (typeof alias === 'string' && alias.length > 0) {
                        command.alias(alias);
                    }
                }
            }
            // Add custom options
            if (config.addOptions) {
                config.addOptions(command);
            }
            // Set action handler
            command.action(async (...args) => {
                const options = args.at(-2);
                const commandArgs = args.slice(0, -2);
                options.args = commandArgs;
                try {
                    await config.execute(options);
                }
                catch (error) {
                    if (error instanceof Error) {
                        ErrorFactory.createTryCatchError('Command execution failed', error);
                        ErrorHandler.handle(error, undefined, false);
                        return;
                    }
                    const wrapped = ErrorFactory.createTryCatchError('Command execution failed', error);
                    ErrorHandler.handle(wrapped, undefined, false);
                }
            });
            return command;
        };
        const base = {
            name: config.name,
            description: config.description,
            verbose: false,
            addOptions: config.addOptions,
            getCommand,
            execute: config.execute,
            info: (msg) => ErrorHandler.info(msg),
            success: (msg) => ErrorHandler.success(msg),
            warn: (msg) => ErrorHandler.warn(msg),
            debug: (msg) => ErrorHandler.debug(msg, true),
        };
        return base;
    },
});
