"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmailService = void 0;
const axios_1 = __importDefault(require("axios"));
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const logger_1 = require("../logger");
class EmailService {
    constructor(config) {
        this.config = config;
    }
    /**
     * Sends an email with optional attachments
     */
    async sendEmail(options) {
        try {
            const emailData = {
                to: options.to,
                from: options.from,
                subject: options.subject,
                text: options.text,
                html: options.html,
                attachments: options.attachments || []
            };
            const headers = {
                'Content-Type': 'application/json'
            };
            if (this.config.apiKey) {
                headers['Authorization'] = `Bearer ${this.config.apiKey}`;
            }
            const response = await axios_1.default.post(this.config.url, emailData, {
                headers,
                timeout: 30000 // 30 second timeout
            });
            if (response.status !== 200) {
                throw new Error(`Email service returned status: ${response.status}`);
            }
            logger_1.logger.info(`Email sent successfully to ${options.to}`);
        }
        catch (error) {
            logger_1.logger.error(`Failed to send email: ${error.message}`);
            throw error;
        }
    }
    /**
     * Sends a log dump file via email
     */
    async sendLogDumpEmail(logFilePath, totalLogs, additionalInfo) {
        try {
            // Read the log file content
            const logContent = await fs_1.promises.readFile(logFilePath, 'utf-8');
            const filename = path_1.default.basename(logFilePath);
            const subject = `Log Dump Report - ${new Date().toISOString().split('T')[0]}`;
            const text = `
Log Dump Report

Generated: ${new Date().toISOString()}
Total Logs: ${totalLogs}
File: ${filename}
${additionalInfo ? `Additional Info: ${additionalInfo}` : ''}

The log dump file is attached to this email.
      `;
            const html = `
<h2>Log Dump Report</h2>
<p><strong>Generated:</strong> ${new Date().toISOString()}</p>
<p><strong>Total Logs:</strong> ${totalLogs}</p>
<p><strong>File:</strong> ${filename}</p>
${additionalInfo ? `<p><strong>Additional Info:</strong> ${additionalInfo}</p>` : ''}
<p>The log dump file is attached to this email.</p>
      `;
            const attachment = {
                filename: filename,
                content: Buffer.from(logContent).toString('base64'),
                contentType: 'application/json'
            };
            await this.sendEmail({
                to: this.config.toEmail,
                from: this.config.fromEmail,
                subject,
                text,
                html,
                attachments: [attachment]
            });
            logger_1.logger.info(`Log dump email sent with ${totalLogs} logs`);
        }
        catch (error) {
            logger_1.logger.error(`Failed to send log dump email: ${error}`);
            throw error;
        }
    }
    /**
     * Sends a log purge report via email
     */
    async sendLogPurgeReport(purgedCount, directorySize, retentionDays) {
        try {
            const subject = `Log Purge Report - ${new Date().toISOString().split('T')[0]}`;
            const text = `
Log Purge Report

Generated: ${new Date().toISOString()}
Files Purged: ${purgedCount}
Current Directory Size: ${this.formatBytes(directorySize)}
Retention Period: ${retentionDays} days

Old log files have been successfully purged.
      `;
            const html = `
<h2>Log Purge Report</h2>
<p><strong>Generated:</strong> ${new Date().toISOString()}</p>
<p><strong>Files Purged:</strong> ${purgedCount}</p>
<p><strong>Current Directory Size:</strong> ${this.formatBytes(directorySize)}</p>
<p><strong>Retention Period:</strong> ${retentionDays} days</p>
<p>Old log files have been successfully purged.</p>
      `;
            await this.sendEmail({
                to: this.config.toEmail,
                from: this.config.fromEmail,
                subject,
                text,
                html
            });
            logger_1.logger.info(`Log purge report sent - ${purgedCount} files purged`);
        }
        catch (error) {
            logger_1.logger.error(`Failed to send log purge report: ${error}`);
            throw error;
        }
    }
    /**
     * Sends a general log service notification
     */
    async sendLogServiceNotification(title, message, level = 'info') {
        try {
            const subject = `Log Service ${level.toUpperCase()}: ${title}`;
            const text = `
${title}

${message}

Generated: ${new Date().toISOString()}
      `;
            const html = `
<h2>${title}</h2>
<p>${message}</p>
<p><strong>Generated:</strong> ${new Date().toISOString()}</p>
      `;
            await this.sendEmail({
                to: this.config.toEmail,
                from: this.config.fromEmail,
                subject,
                text,
                html
            });
            logger_1.logger.info(`Log service notification sent: ${title}`);
        }
        catch (error) {
            logger_1.logger.error(`Failed to send log service notification: ${error}`);
            throw error;
        }
    }
    formatBytes(bytes) {
        if (bytes === 0)
            return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
}
exports.EmailService = EmailService;
//# sourceMappingURL=emailService.js.map