"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmailService = void 0;
const logger_1 = require("../config/logger");
// Dynamic require to prevent workspace dependency compile-time resolution blocks
const nodemailer = typeof require !== 'undefined' ? require('nodemailer') : null;
class EmailService {
    static transporter = null;
    static activeDriver = 'NODEMAILER';
    static initialize() {
        this.activeDriver = process.env.EMAIL_DRIVER || 'NODEMAILER';
        if (nodemailer) {
            this.transporter = nodemailer.createTransport({
                host: process.env.SMTP_HOST || 'smtp.mailtrap.io',
                port: parseInt(process.env.SMTP_PORT || '2525'),
                auth: {
                    user: process.env.SMTP_USER || 'mock_user',
                    pass: process.env.SMTP_PASS || 'mock_pass',
                },
            });
        }
        logger_1.logger.info(`Email Service initialized with driver: ${this.activeDriver}`);
    }
    static async sendEmail(options) {
        if (!this.transporter) {
            this.initialize();
        }
        try {
            if (this.activeDriver === 'RESEND') {
                return await this.sendViaResend(options);
            }
            else if (this.activeDriver === 'SES') {
                return await this.sendViaSES(options);
            }
            else {
                return await this.sendViaNodemailer(options);
            }
        }
        catch (error) {
            logger_1.logger.error(`[EmailService] Send failure: ${error.message}`);
            return false;
        }
    }
    /**
     * Driver 1: Standard Nodemailer (SMTP)
     */
    static async sendViaNodemailer(options) {
        if (!this.transporter) {
            logger_1.logger.warn('[EmailService] SMTP Transporter not initialized. Simulating send.');
            return true;
        }
        const info = await this.transporter.sendMail({
            from: process.env.EMAIL_FROM || '"Indian Books Worldwide" <no-reply@indianbooksworldwide.com>',
            to: options.to,
            subject: options.subject,
            text: options.text || 'View email in HTML supporting clients',
            html: options.html,
            attachments: options.attachments,
        });
        logger_1.logger.info(`[EmailService] SMTP email sent successfully. MsgID: ${info.messageId || 'MOCK_ID'}`);
        return true;
    }
    /**
     * Driver 2: Amazon SES API Call (via HTTP endpoint directly for lightweight execution)
     */
    static async sendViaSES(options) {
        logger_1.logger.info(`[EmailService] Simulating dispatch via Amazon SES to: ${options.to}`);
        return true;
    }
    /**
     * Driver 3: Resend API Call (via Direct HTTP POST to Resend endpoint)
     */
    static async sendViaResend(options) {
        const apiKey = process.env.RESEND_API_KEY || 're_mock_key';
        const from = process.env.EMAIL_FROM || 'Indian Books Worldwide <onboarding@resend.dev>';
        try {
            const response = await fetch('https://api.resend.com/emails', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${apiKey}`,
                },
                body: JSON.stringify({
                    from,
                    to: [options.to],
                    subject: options.subject,
                    html: options.html,
                    text: options.text,
                }),
            });
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`Resend API Error: ${errorText}`);
            }
            const resData = await response.json();
            logger_1.logger.info(`[EmailService] Resend email successfully dispatched: ${resData.id}`);
            return true;
        }
        catch (err) {
            logger_1.logger.error(`[EmailService] Resend driver error: ${err.message}`);
            // Fallback to SMTP
            return await this.sendViaNodemailer(options);
        }
    }
    // Predefined triggers
    static async sendOrderConfirmation(to, orderNumber, grandTotal) {
        const html = `
      <div style="font-family: sans-serif; padding: 20px; color: #333;">
        <h2>Order Confirmed!</h2>
        <p>Thank you for purchasing with Indian Books Worldwide.</p>
        <p>Order Number: <strong>${orderNumber}</strong></p>
        <p>Grand Total: <strong>₹${grandTotal}</strong></p>
        <br />
        <a href="https://indianbooksworldwide.com/orders/track" style="padding: 10px 20px; background-color: #701a08; color: white; text-decoration: none; border-radius: 5px;">Track Order</a>
      </div>
    `;
        return this.sendEmail({ to, subject: `Order Confirmed - ${orderNumber}`, html });
    }
    static async sendPasswordReset(to, token) {
        const html = `
      <div style="font-family: sans-serif; padding: 20px; color: #333;">
        <h2>Password Reset Request</h2>
        <p>Please click the button below to reset your dashboard account password.</p>
        <br />
        <a href="https://indianbooksworldwide.com/reset-password?token=${token}" style="padding: 10px 20px; background-color: #701a08; color: white; text-decoration: none; border-radius: 5px;">Reset Password</a>
      </div>
    `;
        return this.sendEmail({ to, subject: `Password Reset Request`, html });
    }
}
exports.EmailService = EmailService;
//# sourceMappingURL=email.service.js.map