import { Env } from '../../config/env.js';
import { Logger } from '../../config/logger.js';
import { JobReconciliationRunner } from './JobReconciliationRunner.js';
import { JobRecoveryDaemon } from './JobRecoveryDaemon.js';
import { StalledJobMonitor } from './StalledJobMonitor.js';
const isUnrefableTimer = (timer) => {
    return (typeof timer === 'object' &&
        timer !== null &&
        'unref' in timer &&
        typeof timer.unref === 'function');
};
const state = {
    started: false,
};
const clearTimer = (timer) => {
    if (timer === undefined)
        return;
    clearInterval(timer);
};
const startInterval = (handler, intervalMs) => {
    const timer = setInterval(() => {
        handler().catch((error) => {
            Logger.warn('Queue reliability interval failed', {
                error: error instanceof Error ? error : String(error),
            });
        });
    }, intervalMs);
    if (isUnrefableTimer(timer)) {
        timer.unref();
    }
    return timer;
};
export const QueueReliabilityOrchestrator = Object.freeze({
    isEnabled() {
        return Env.getBool('JOB_RELIABILITY_ENABLED', true);
    },
    start() {
        if (!this.isEnabled())
            return;
        if (state.started)
            return;
        const reconciliationMs = Math.max(5000, Env.getInt('JOB_RECONCILIATION_INTERVAL_MS', 60000));
        const recoveryMs = Math.max(5000, Env.getInt('JOB_RECOVERY_INTERVAL_MS', 30000));
        const stalledMs = Math.max(5000, Env.getInt('STALLED_JOB_CHECK_INTERVAL_MS', 30000));
        state.reconciliationTimer = startInterval(async () => {
            await JobReconciliationRunner.runOnce();
        }, reconciliationMs);
        state.recoveryTimer = startInterval(async () => {
            await JobRecoveryDaemon.runOnce();
        }, recoveryMs);
        state.stalledTimer = startInterval(async () => {
            await StalledJobMonitor.scanOnce();
        }, stalledMs);
        state.started = true;
        Logger.info('Queue reliability orchestrator started', {
            reconciliationMs,
            recoveryMs,
            stalledMs,
        });
    },
    stop() {
        clearTimer(state.reconciliationTimer);
        clearTimer(state.recoveryTimer);
        clearTimer(state.stalledTimer);
        state.reconciliationTimer = undefined;
        state.recoveryTimer = undefined;
        state.stalledTimer = undefined;
        state.started = false;
    },
});
export default QueueReliabilityOrchestrator;
