/**
 * Slack Initializer
 *
 * Handles automatic Slack connection on application startup.
 * Checks for environment variables and initializes if configured.
 *
 * @module services/slack/initializer
 */
import { getSlackService } from './slack.service.js';
import { getSlackOrchestratorBridge } from './slack-orchestrator-bridge.js';
import { loadSlackCredentials } from './slack-credentials.service.js';
import { LoggerService } from '../core/logger.service.js';
const logger = LoggerService.getInstance().createComponentLogger('SlackInitializer');
/**
 * Check if Slack is configured via environment variables
 *
 * @returns True if all required environment variables are set
 */
export function isSlackConfigured() {
    return !!(process.env.SLACK_BOT_TOKEN &&
        process.env.SLACK_APP_TOKEN &&
        process.env.SLACK_SIGNING_SECRET);
}
/**
 * Get Slack configuration from environment variables
 *
 * @returns SlackConfig object or null if not configured
 */
export function getSlackConfigFromEnv() {
    const botToken = process.env.SLACK_BOT_TOKEN;
    const appToken = process.env.SLACK_APP_TOKEN;
    const signingSecret = process.env.SLACK_SIGNING_SECRET;
    if (!botToken || !appToken || !signingSecret) {
        return null;
    }
    return {
        botToken,
        appToken,
        signingSecret,
        defaultChannelId: process.env.SLACK_DEFAULT_CHANNEL,
        allowedUserIds: process.env.SLACK_ALLOWED_USERS?.split(',').filter(Boolean),
        socketMode: true,
    };
}
/**
 * Get Slack configuration from environment variables or saved credentials.
 * Environment variables take priority over saved credentials.
 *
 * @returns SlackConfig object or null if not configured
 */
export async function getSlackConfig() {
    // Env vars take priority
    const envConfig = getSlackConfigFromEnv();
    if (envConfig) {
        return envConfig;
    }
    // Fall back to saved credentials
    try {
        const savedConfig = await loadSlackCredentials();
        if (savedConfig) {
            logger.info('Loaded Slack credentials from saved config');
            return savedConfig;
        }
    }
    catch (error) {
        logger.warn('Failed to load saved Slack credentials', {
            error: error instanceof Error ? error.message : String(error),
        });
    }
    return null;
}
/**
 * Initialize Slack integration if configured via environment variables
 * or saved credentials.
 *
 * This function is designed to be called during application startup.
 * It safely handles cases where Slack is not configured.
 *
 * @param options - Optional initialization options
 * @returns Result object indicating success or failure
 *
 * @example
 * ```typescript
 * const result = await initializeSlackIfConfigured({
 *   agentRegistrationService: myService
 * });
 * if (result.success) {
 *   console.log('Slack connected!');
 * } else if (result.attempted) {
 *   console.error('Slack failed to connect:', result.error);
 * } else {
 *   console.log('Slack not configured, skipping');
 * }
 * ```
 */
export async function initializeSlackIfConfigured(options) {
    const config = await getSlackConfig();
    if (!config) {
        logger.info('Not configured - skipping initialization');
        return { attempted: false, success: false };
    }
    try {
        const slackService = getSlackService();
        await slackService.initialize(config);
        const bridge = getSlackOrchestratorBridge();
        // Set the message queue service if provided
        if (options?.messageQueueService) {
            bridge.setMessageQueueService(options.messageQueueService);
        }
        await bridge.initialize();
        logger.info('Successfully connected');
        return { attempted: true, success: true };
    }
    catch (error) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        logger.error('Failed to initialize', { error: errorMessage });
        return { attempted: true, success: false, error: errorMessage };
    }
}
/**
 * Gracefully shutdown Slack integration
 *
 * Call this during application shutdown to disconnect cleanly.
 */
export async function shutdownSlack() {
    try {
        const slackService = getSlackService();
        if (slackService.isConnected()) {
            await slackService.disconnect();
            logger.info('Disconnected');
        }
    }
    catch (error) {
        logger.error('Error during shutdown', { error: error instanceof Error ? error.message : String(error) });
    }
}
//# sourceMappingURL=slack-initializer.js.map