import { getApplicationOrVersionNamesCompletion } from './completions.js';
import { createApplicationVersionMetadata } from './application-version-metadata.js';
import { resolveApplicationVersion } from './version-resolver.js';

/**
 * Factory function to create command handlers that work with application versions
 * This eliminates code duplication across commands like logs, ai-analyze, etc.
 *
 * @param {Object} config - Configuration object
 * @param {string} config.name - Command name
 * @param {string} config.desc - Command description
 * @param {string} config.usage - Command usage string
 * @param {Function} config.serviceCall - Async function to call the service
 *                   (receives { console, profile, fetch, application, version })
 * @param {Function} config.formatOutput - Function to format the service call
 *                   result for output (receives the service result)
 * @returns {Object} Command object with getMetadata, getCompletion, and run
 */
export const createApplicationVersionCommand = ({ name, desc, usage, serviceCall, formatOutput }) => {
    return {
        getMetadata: () => createApplicationVersionMetadata({ name, desc, usage }),

        getCompletion: getApplicationOrVersionNamesCompletion({ versionCompletion: true }),

        run: async ({ args, config, console, fetch }) => {
            const profile = config?.profiles?.[config?.active_profile];

            const version = await resolveApplicationVersion({
                application: args.application,
                version: args.version,
                console,
                profile,
                fetch
            });

            console.debug(`${desc} for application '${args.application}' version '${version}'`);

            const result = await serviceCall({
                console,
                profile,
                fetch,
                application: args.application,
                version
            });

            return formatOutput(result);
        }
    };
};
