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

const port = parseInt(process.env.EMAIL_PORT || '587', 10);
const secure = process.env.EMAIL_SECURE === 'true';

const transporterConfig = process.env.EMAIL_HOST ? {
    host: process.env.EMAIL_HOST,
    port,
    secure,
    // Port 587 uses STARTTLS (opportunistic TLS). requireTLS: true ensures the connection
    // is always upgraded to TLS, preventing Gmail's "530 Must issue a STARTTLS command first" error.
    requireTLS: !secure && port === 587,
    ...(process.env.EMAIL_USER && process.env.EMAIL_PASS ? {
        auth: {
            user: process.env.EMAIL_USER,
            pass: process.env.EMAIL_PASS
        }
    } : {})
} : {
    service: process.env.EMAIL_SERVICE || 'Gmail',
    auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS
    }
};

const transporter = nodemailer.createTransport(transporterConfig);

module.exports = transporter;
