import { LogError, LogStatus } from '@memberjunction/core';
import { UserCache } from '@memberjunction/sqlserver-dataprovider';
import { SchedulingEngine } from '@memberjunction/scheduling-engine';
export class ScheduledJobsService {
    engine;
    systemUser = null;
    isRunning = false;
    config;
    constructor(config) {
        this.config = config;
        this.engine = SchedulingEngine.Instance;
    }
    async Initialize() {
        if (!this.config.enabled) {
            LogStatus('[ScheduledJobsService] Scheduled jobs are disabled in configuration');
            return;
        }
        try {
            this.systemUser = await this.getSystemUser();
            if (!this.systemUser) {
                throw new Error(`System user not found with email: ${this.config.systemUserEmail}`);
            }
            await this.engine.Config(false, this.systemUser);
        }
        catch (error) {
            LogError('[ScheduledJobsService] Failed to initialize', undefined, error);
            throw error;
        }
    }
    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;
            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 {
                    console.log(`📅 Scheduled Jobs: ${jobCount} active job(s), polling interval not set`);
                }
            }
        }
        catch (error) {
            LogError('[ScheduledJobsService] Failed to start polling', undefined, error);
            throw error;
        }
    }
    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;
        }
    }
    async getSystemUser() {
        const systemUserEmail = this.config.systemUserEmail;
        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;
    }
    GetStatus() {
        return {
            enabled: this.config.enabled,
            running: this.isRunning,
            activeJobs: this.engine?.ScheduledJobs?.length || 0,
            pollingInterval: this.engine?.ActivePollingInterval || 0
        };
    }
    get IsEnabled() {
        return this.config.enabled;
    }
    get IsRunning() {
        return this.isRunning;
    }
}
//# sourceMappingURL=ScheduledJobsService.js.map