const nodemailer = require('nodemailer');
const errorHandling = require('../error_handling');

const transporter = nodemailer.createTransport({
    host: 'email-smtp.us-east-1.amazonaws.com', // e.g., email-smtp.us-east-1.amazonaws.com
    port: 587,
    secure: false,
    auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASSWORD,
    },
});

const sendEmail = async ({ to, subject, html }) => {
    const timestamp = new Date().toLocaleString('en-US', {
        timeZone: 'America/New_York',
        timeZoneName: 'short', // e.g. EDT
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: 'numeric',
        minute: '2-digit',
    });

    const mailOptions = {
        from: '"ShipME" <noreply@shipmeapp.com>',
        to,
        subject,
        html: `
        <div style="max-width: 35rem; margin: 0px auto;">
            <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="margin-bottom: 1.5rem;">
                <tbody>
                    <tr>
                        <td align="center">
                            <img src="https://shipmeapp.com/src/assets/ShipME_logo.png" alt="ShipME Logo" style="display: block;" width="300">
                        </td>
                    </tr>
                </tbody>
            </table>
            <hr style="margin: 1rem 0; border: none; border-top: 1px solid #eee;" />
            ${html}
            <hr style="margin: 1rem 0; border: none; border-top: 1px solid #eee;" />
            <p style="color: #999999; margin-bottom: 0px;">This is an automated notification from ShipME. 
                <a href="https://shipmeapp.com/settings">Update your notification settings.</a>
            </p>
            <span style="font-size: 0.75rem; color: #bbb;">Sent on ${timestamp}.</span>
        </div>
    `,
    };

    try {
        await transporter.sendMail(mailOptions);
        return { success: true, message: `Email sent to ${to}` };
    } catch (error) {
        return {
            success: false,
            message: `Failed to send email: ${error.message}`,
        };
    }
};

module.exports = { sendEmail };
