const nodemailer = require('nodemailer');
require('dotenv').config();

// Create a transport configuration for Postfix
const transport = nodemailer.createTransport({
    host: '172.18.0.3',  // Use the Docker service name for Postfix
    // or host: 'mail', // depending on your docker-compose service name
    port: 587,         // Default SMTP port
    secure: false,    // TLS is not required for local Postfix
    auth: {
        user: process.env.SMTP_USER,     // Add your SMTP username
        pass: process.env.SMTP_PASS      // Add your SMTP password
    },
    tls: {
        rejectUnauthorized: false // Allow self-signed certificates
    }
});

/**
 * Sends an email using the configured Postfix transport
 * @param {string} to - Recipient email address
 * @param {string} subject - Email subject
 * @param {string} text - Plain text email content
 * @param {string} html - HTML email content (optional)
 * @returns {Promise} Result of sending the email
 */
async function sendMail(to, subject, text, html) {
    try {
        const mailOptions = {
            from: process.env.SMTP_FROM,
            to: to,
            subject: subject,
            text: text,
            html: html || text
        };

        const info = await transport.sendMail(mailOptions);
        console.log('Email sent successfully:', info.messageId);
        return info;
    } catch (error) {
        console.error('Error sending email:', error);
        throw error;
    }
}

module.exports = sendMail;