"use strict";
/**
 * Stop Command
 * Issue #96: npm install CLI support
 * Issue #125: Use getPidFilePath for correct path resolution
 * Issue #136: Add --issue flag for worktree-specific server stop
 * Stop CommandMate server
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.stopCommand = stopCommand;
const types_1 = require("../types");
const logger_1 = require("../utils/logger");
const daemon_1 = require("../utils/daemon");
const security_logger_1 = require("../utils/security-logger");
const env_setup_1 = require("../utils/env-setup");
const input_validators_1 = require("../utils/input-validators");
const logger = new logger_1.CLILogger();
/**
 * Execute stop command
 * Issue #125: Use getPidFilePath for correct path resolution
 * Issue #136: Support --issue flag for worktree-specific server stop
 */
async function stopCommand(options) {
    try {
        // Issue #136: Validate issue number if provided
        if (options.issue !== undefined) {
            const validation = (0, input_validators_1.validateIssueNoResult)(options.issue);
            if (!validation.valid) {
                logger.error(`Invalid issue number: ${validation.error}`);
                process.exit(types_1.ExitCode.STOP_FAILED);
                return;
            }
        }
        // Issue #125: Get PID file path from correct location
        // Issue #136: Use issue number for worktree-specific PID file
        const pidFilePath = (0, env_setup_1.getPidFilePath)(options.issue);
        const daemonManager = new daemon_1.DaemonManager(pidFilePath);
        // Issue #136: Show which server we're stopping
        const serverLabel = options.issue !== undefined
            ? `Issue #${options.issue} server`
            : 'Main server';
        // Check if running
        if (!(await daemonManager.isRunning())) {
            const status = await daemonManager.getStatus();
            if (status === null) {
                logger.info(`${serverLabel} is not running (no PID file found)`);
                logger.info('Status: Stopped');
            }
            else {
                logger.info(`${serverLabel} is not running (stale PID file)`);
            }
            process.exit(types_1.ExitCode.SUCCESS);
            return;
        }
        const status = await daemonManager.getStatus();
        const pid = status?.pid;
        if (options.force) {
            logger.warn(`Force stopping ${serverLabel} (PID: ${pid})...`);
            (0, security_logger_1.logSecurityEvent)({
                timestamp: new Date().toISOString(),
                command: 'stop',
                action: 'warning',
                details: `--force flag used (SIGKILL) on PID ${pid}${options.issue !== undefined ? ` (Issue #${options.issue})` : ''}`,
            });
        }
        else {
            logger.info(`Stopping ${serverLabel} (PID: ${pid})...`);
        }
        const result = await daemonManager.stop(options.force);
        if (result) {
            logger.success(`${serverLabel} stopped`);
            (0, security_logger_1.logSecurityEvent)({
                timestamp: new Date().toISOString(),
                command: 'stop',
                action: 'success',
                details: `Server stopped (PID: ${pid})${options.issue !== undefined ? ` (Issue #${options.issue})` : ''}`,
            });
            process.exit(types_1.ExitCode.SUCCESS);
        }
        else {
            logger.error(`Failed to stop ${serverLabel}`);
            (0, security_logger_1.logSecurityEvent)({
                timestamp: new Date().toISOString(),
                command: 'stop',
                action: 'failure',
                details: `Failed to stop PID ${pid}${options.issue !== undefined ? ` (Issue #${options.issue})` : ''}`,
            });
            process.exit(types_1.ExitCode.STOP_FAILED);
        }
    }
    catch (error) {
        const message = (0, types_1.getErrorMessage)(error);
        logger.error(`Stop failed: ${message}`);
        (0, security_logger_1.logSecurityEvent)({
            timestamp: new Date().toISOString(),
            command: 'stop',
            action: 'failure',
            details: message,
        });
        process.exit(types_1.ExitCode.UNEXPECTED_ERROR);
    }
}
