import { performUpgrade } from "../tools/upgrade.js";
import { addCommandIdToPendingUpgrade } from "../config/index.js";
import { logger } from "../logger.js";
/**
 * Creates a CommandHandler for the "upgrade" remote command.
 * Delegates to the same performUpgrade() logic used by the MCP upgrade tool.
 */
export function createUpgradeHandler() {
    return createUpgradeHandlerWithOptions();
}
/**
 * Creates a CommandHandler for the "upgrade_beta" remote command.
 * Same as upgrade but targets the beta npm dist-tag.
 */
export function createUpgradeBetaHandler() {
    return createUpgradeHandlerWithOptions({ beta: true, force: true });
}
function createUpgradeHandlerWithOptions(defaults) {
    return async (commandId, _payload) => {
        const label = defaults?.beta ? "upgrade-beta" : defaults?.tag ? `upgrade-${defaults.tag}` : "upgrade";
        try {
            logger.system(`[upgrade-handler] Received remote ${label} command`);
            const result = await performUpgrade(defaults);
            logger.system(`[upgrade-handler] ${result.message}`);
            if (result.ok) {
                addCommandIdToPendingUpgrade(commandId);
            }
            return {
                status: result.ok ? "completed" : "failed",
                result: JSON.stringify({ message: result.message }),
            };
        }
        catch (err) {
            const errMsg = err instanceof Error ? err.message : String(err);
            logger.err(`[upgrade-handler] ${label} failed: ${errMsg}`);
            return {
                status: "failed",
                result: JSON.stringify({ error: errMsg }),
            };
        }
    };
}
//# sourceMappingURL=upgrade-handler.js.map