"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchedulerService = void 0;
const backup_service_1 = require("./backup.service");
const logger_1 = require("../config/logger");
class SchedulerService {
    static dailyTimer = null;
    static initialize() {
        logger_1.logger.info('Scheduler Service: Initializing background cron jobs...');
        // Run database and file backups daily (every 24 hours)
        const dailyIntervalMs = 24 * 60 * 60 * 1000;
        this.dailyTimer = setInterval(async () => {
            logger_1.logger.info('Scheduler Service: Running daily cron heartbeat tasks...');
            try {
                // 1. Run database SQL table dumps
                await backup_service_1.BackupService.backupDatabase();
                // 2. Run media files manifests backups
                await backup_service_1.BackupService.backupMediaFiles();
                // 3. Clear temporary files and expired log data
                await this.clearLogCaches();
                logger_1.logger.info('Scheduler Service: All daily scheduled cron operations completed successfully.');
            }
            catch (err) {
                logger_1.logger.error(`Scheduler Service: Cron tasks error: ${err.message}`);
            }
        }, dailyIntervalMs);
        // Run initial backup trigger 10 seconds after server boot to verify integrations
        setTimeout(async () => {
            logger_1.logger.info('Scheduler Service: Triggering boot-time sanity backup checks...');
            try {
                await backup_service_1.BackupService.backupDatabase();
                await backup_service_1.BackupService.backupMediaFiles();
            }
            catch (err) {
                logger_1.logger.error(`Scheduler Service: Boot-time checks failure: ${err.message}`);
            }
        }, 10000);
    }
    static async clearLogCaches() {
        logger_1.logger.info('Scheduler Service: Cleaning temporary logs cache databases...');
        // We can clear expired user login sessions or temporary webhook logs.
        // e.g. delete WebhookLog older than 90 days
        try {
            const boundaryDate = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
            logger_1.logger.info(`Scheduler Service: Logs cleaned up successfully up to: ${boundaryDate.toISOString()}`);
        }
        catch (err) {
            logger_1.logger.error(`Scheduler Service: Logs cleanup failed: ${err.message}`);
        }
    }
    static stop() {
        if (this.dailyTimer) {
            clearInterval(this.dailyTimer);
            this.dailyTimer = null;
            logger_1.logger.info('Scheduler Service: Cron job timer stopped.');
        }
    }
}
exports.SchedulerService = SchedulerService;
//# sourceMappingURL=scheduler.service.js.map