"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.startScheduler = startScheduler;
exports.stopScheduler = stopScheduler;
exports.restartScheduler = restartScheduler;
exports.isSchedulerRunning = isSchedulerRunning;
const config_1 = require("./config");
const engine_1 = require("./engine");
let timer = null;
let running = false;
function startScheduler(onProgress) {
    stopScheduler();
    const config = (0, config_1.getBackupConfig)();
    if (!config.schedule.enabled)
        return;
    const intervalMs = config.schedule.intervalMinutes * 60 * 1000;
    console.log(`[Backup] Scheduler started: every ${config.schedule.intervalMinutes} minutes`);
    const interval = setInterval(async () => {
        if (running) {
            console.log('[Backup] Skipping scheduled backup — previous one still running');
            return;
        }
        running = true;
        try {
            console.log('[Backup] Scheduled backup starting...');
            const results = await (0, engine_1.runBackupAll)(onProgress);
            const ok = results.filter((r) => r.status === 'success').length;
            const fail = results.filter((r) => r.status === 'failed').length;
            console.log(`[Backup] Scheduled backup done: ${ok} success, ${fail} failed`);
        }
        catch (err) {
            console.error('[Backup] Scheduled backup error:', err);
        }
        finally {
            running = false;
        }
    }, intervalMs);
    interval.unref();
    timer = interval;
}
function stopScheduler() {
    if (timer) {
        clearInterval(timer);
        timer = null;
        console.log('[Backup] Scheduler stopped');
    }
}
function restartScheduler(onProgress) {
    stopScheduler();
    startScheduler(onProgress);
}
function isSchedulerRunning() {
    return timer !== null;
}
//# sourceMappingURL=scheduler.js.map