"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LogManagementService = void 0;
const logDumpService_1 = require("./logDumpService");
const emailService_1 = require("./emailService");
const logPurgeService_1 = require("./logPurgeService");
const logger_1 = require("../logger");
class LogManagementService {
    constructor(config) {
        this.dumpTimer = null;
        this.purgeTimer = null;
        this.config = config;
        // Initialize services
        this.logDumpService = new logDumpService_1.LogDumpService({
            logsDirectory: config.logsDirectory,
            retentionDays: config.retentionDays,
            emailConfig: config.emailConfig
        });
        this.emailService = new emailService_1.EmailService(config.emailConfig);
        this.logPurgeService = new logPurgeService_1.LogPurgeService({
            logsDirectory: config.logsDirectory,
            retentionDays: config.retentionDays
        });
        // Start scheduled tasks
        this.startScheduledTasks();
    }
    /**
     * Starts scheduled log dumping and purging
     */
    startScheduledTasks() {
        const dumpInterval = (this.config.dumpIntervalHours || 24) * 60 * 60 * 1000;
        const purgeInterval = (this.config.purgeIntervalHours || 24) * 60 * 60 * 1000;
        // Schedule log dumping
        this.dumpTimer = setInterval(async () => {
            try {
                await this.performLogDump();
            }
            catch (error) {
                logger_1.logger.error(`Scheduled log dump failed: ${error}`);
            }
        }, dumpInterval);
        // Schedule log purging
        this.purgeTimer = setInterval(async () => {
            try {
                await this.performLogPurge();
            }
            catch (error) {
                logger_1.logger.error(`Scheduled log purge failed: ${error}`);
            }
        }, purgeInterval);
        logger_1.logger.info(`Log management service started - dump every ${this.config.dumpIntervalHours || 24}h, purge every ${this.config.purgeIntervalHours || 24}h`);
    }
    /**
     * Performs a complete log dump and sends via email
     */
    async performLogDump() {
        try {
            logger_1.logger.info('Starting log dump process');
            // Read all logs
            const allLogs = await this.logDumpService.readAllLogs();
            if (allLogs.length === 0) {
                logger_1.logger.info('No logs found to dump');
                return;
            }
            // Create timestamped dump file
            const dumpFilePath = await this.logDumpService.dumpLogsToFile(allLogs);
            // Send via email
            await this.emailService.sendLogDumpEmail(dumpFilePath, allLogs.length, `Log dump generated at ${new Date().toISOString()}`);
            logger_1.logger.info(`Log dump completed - ${allLogs.length} logs dumped and emailed`);
        }
        catch (error) {
            logger_1.logger.error(`Log dump process failed: ${error}`);
            throw error;
        }
    }
    /**
     * Performs log purging and sends report via email
     */
    async performLogPurge() {
        try {
            logger_1.logger.info('Starting log purge process');
            // Get stats before purging
            const statsBefore = await this.logPurgeService.getLogsDirectoryStats();
            // Perform purge
            const purgeResult = await this.logPurgeService.purgeOldLogs();
            // Get stats after purging
            const statsAfter = await this.logPurgeService.getLogsDirectoryStats();
            // Send purge report via email
            await this.emailService.sendLogPurgeReport(purgeResult.filesPurged, statsAfter.totalSize, this.config.retentionDays);
            logger_1.logger.info(`Log purge completed - ${purgeResult.filesPurged} files purged, ${this.formatBytes(purgeResult.spaceFreed)} freed`);
        }
        catch (error) {
            logger_1.logger.error(`Log purge process failed: ${error}`);
            throw error;
        }
    }
    /**
     * Internal method for automatic log dump (called by scheduler)
     */
    async triggerLogDump() {
        logger_1.logger.info('Automatic log dump triggered');
        await this.performLogDump();
    }
    /**
     * Internal method for automatic log purge (called by scheduler)
     */
    async triggerLogPurge() {
        logger_1.logger.info('Automatic log purge triggered');
        await this.performLogPurge();
    }
    /**
     * Gets comprehensive logs directory statistics
     */
    async getLogsDirectoryStats() {
        const stats = await this.logPurgeService.getLogsDirectoryStats();
        return {
            ...stats,
            retentionDays: this.config.retentionDays
        };
    }
    /**
     * Internal method to send status notifications (called automatically)
     */
    async sendStatusNotification() {
        try {
            const stats = await this.getLogsDirectoryStats();
            const message = `
Log Management Service Status

Directory: ${this.config.logsDirectory}
Total Files: ${stats.totalFiles}
Total Size: ${this.formatBytes(stats.totalSize)}
Oldest File: ${stats.oldestFile ? stats.oldestFile.toISOString() : 'None'}
Newest File: ${stats.newestFile ? stats.newestFile.toISOString() : 'None'}
Retention Period: ${stats.retentionDays} days

Files by Age:
${Object.entries(stats.filesByAge).map(([age, count]) => `  ${age}: ${count} files`).join('\n')}

Scheduled Tasks:
- Log Dump: Every ${this.config.dumpIntervalHours || 24} hours
- Log Purge: Every ${this.config.purgeIntervalHours || 24} hours
      `;
            await this.emailService.sendLogServiceNotification('Log Management Service Status', message, 'info');
        }
        catch (error) {
            logger_1.logger.error(`Failed to send status notification: ${error}`);
        }
    }
    /**
     * Stops the log management service and clears timers
     */
    stop() {
        if (this.dumpTimer) {
            clearInterval(this.dumpTimer);
            this.dumpTimer = null;
        }
        if (this.purgeTimer) {
            clearInterval(this.purgeTimer);
            this.purgeTimer = null;
        }
        logger_1.logger.info('Log management service stopped');
    }
    /**
     * Formats bytes into human-readable format
     */
    formatBytes(bytes) {
        if (bytes === 0)
            return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
}
exports.LogManagementService = LogManagementService;
//# sourceMappingURL=logManagementService.js.map