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 sendEmail(to, subject, text, html) {
    try {
        const mailOptions = {
            from: process.env.SMTP_FROM, // Replace with your sender email
            to: to,
            subject: subject,
            text: text,
            html: html || text // Use HTML if provided, otherwise use plain 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;
    }
}

// Example usage
async function main() {
    try {
        await sendEmail(
            'ryancarr10@gmail.com',
            'Test Email',
            'This is a test email from Postfix',
            '<h1>This is a test email from Postfix</h1>'
        );
    } catch (error) {
        console.error('Main error:', error);
    }
}

main();
