/**
 * @fileoverview Service module for managing scheduled job lifecycle
 * @module MJServer/services
 */
import { LogError, LogStatus } from '@memberjunction/core';
import { UserCache } from '@memberjunction/sqlserver-dataprovider';
import { SchedulingEngine } from '@memberjunction/scheduling-engine';
/**
 * Service for managing scheduled jobs lifecycle
 * Handles initialization, starting/stopping polling, and graceful shutdown
 */
export class ScheduledJobsService {
    constructor(config) {
        this.systemUser = null;
        this.isRunning = false;
        this.config = config;
        this.engine = SchedulingEngine.Instance;
    }
    /**
     * Initialize the scheduled jobs service
     * Loads metadata and prepares the engine
     */
    async Initialize() {
        if (!this.config.enabled) {
            LogStatus('[ScheduledJobsService] Scheduled jobs are disabled in configuration');
            return;
        }
        try {
            // Get system user for job execution
            this.systemUser = await this.getSystemUser();
            if (!this.systemUser) {
                throw new Error(`System user not found with email: ${this.config.systemUserEmail}`);
            }
            // Pre-load metadata cache
            await this.engine.Config(false, this.systemUser);
        }
        catch (error) {
            LogError('[ScheduledJobsService] Failed to initialize', undefined, error);
            throw error;
        }
    }
    /**
     * Start the scheduled jobs polling
     */
    async Start() {
        if (!this.config.enabled) {
            return;
        }
        if (this.isRunning) {
            LogStatus('[ScheduledJobsService] Already running');
            return;
        }
        if (!this.systemUser) {
            throw new Error('Service not initialized - call Initialize() first');
        }
        try {
            this.engine.StartPolling(this.systemUser);
            this.isRunning = true;
            // Single consolidated console message
            const jobCount = this.engine.ScheduledJobs.length;
            if (jobCount === 0) {
                console.log(`📅 Scheduled Jobs: No active jobs, polling suspended (will auto-start when jobs are added)`);
            }
            else {
                const interval = this.engine.ActivePollingInterval;
                if (interval !== null) {
                    const intervalDisplay = interval >= 60000
                        ? `${Math.round(interval / 60000)} minute(s)`
                        : `${Math.round(interval / 1000)} second(s)`;
                    console.log(`📅 Scheduled Jobs: ${jobCount} active job(s), polling every ${intervalDisplay}`);
                }
                else {
                    // This shouldn't happen if jobCount > 0, but handle it gracefully
                    console.log(`📅 Scheduled Jobs: ${jobCount} active job(s), polling interval not set`);
                }
            }
        }
        catch (error) {
            LogError('[ScheduledJobsService] Failed to start polling', undefined, error);
            throw error;
        }
    }
    /**
     * Stop the scheduled jobs polling gracefully
     */
    async Stop() {
        if (!this.isRunning) {
            return;
        }
        try {
            LogStatus('[ScheduledJobsService] Stopping scheduled job polling');
            this.engine.StopPolling();
            this.isRunning = false;
            LogStatus('[ScheduledJobsService] Polling stopped successfully');
        }
        catch (error) {
            LogError('[ScheduledJobsService] Error stopping polling', undefined, error);
            throw error;
        }
    }
    /**
     * Get the system user for job execution
     * Uses the email configured in scheduledJobs.systemUserEmail
     */
    async getSystemUser() {
        const systemUserEmail = this.config.systemUserEmail;
        // Search UserCache for system user
        const user = UserCache.Users.find(u => u.Email?.toLowerCase() === systemUserEmail.toLowerCase());
        if (user) {
            return user;
        }
        LogError(`[ScheduledJobsService] System user not found with email: ${systemUserEmail}`);
        return null;
    }
    /**
     * Get current service status
     */
    GetStatus() {
        return {
            enabled: this.config.enabled,
            running: this.isRunning,
            activeJobs: this.engine?.ScheduledJobs?.length || 0,
            pollingInterval: this.engine?.ActivePollingInterval || 0
        };
    }
    /**
     * Check if service is enabled in configuration
     */
    get IsEnabled() {
        return this.config.enabled;
    }
    /**
     * Check if service is currently running
     */
    get IsRunning() {
        return this.isRunning;
    }
}
//# sourceMappingURL=ScheduledJobsService.js.map