import nodemailer from 'nodemailer';

let transporterInstance: nodemailer.Transporter | null = null;

function getTransporter() {
    if (transporterInstance) return transporterInstance;

    if (!process.env.MAIL_HOST) {
        throw new Error('MAIL_HOST is not configured. Please check your environment variables.');
    }

    transporterInstance = nodemailer.createTransport({
        host: process.env.MAIL_HOST,
        port: Number(process.env.MAIL_PORT) || 587,
        secure: Number(process.env.MAIL_PORT) === 465,
        auth: {
            user: process.env.MAIL_USERNAME,
            pass: process.env.MAIL_PASSWORD,
        },
    });

    return transporterInstance;
}

interface SendEmailOptions {
    to?: string | string[];
    replyTo?: string;
    subject: string;
    html: string;
}

export async function sendEmail({ to, replyTo, subject, html }: SendEmailOptions) {
    const recipients = to || process.env.MAIL_RECIPIENTS;

    if (!recipients) {
        console.error('No email recipients configured', { subject });
        return { success: false as const, error: 'No recipients configured' };
    }

    if (!process.env.MAIL_FROM) {
        console.error('MAIL_FROM is not configured', { subject, recipients });
        return { success: false as const, error: 'MAIL_FROM is not configured' };
    }

    const mailOptions = {
        from: process.env.MAIL_FROM,
        to: recipients,
        replyTo,
        subject,
        html,
    };

    try {
        const info = await getTransporter().sendMail(mailOptions);
        console.log('Email sent successfully', { messageId: info.messageId, subject, recipients });
        return { success: true, messageId: info.messageId };
    } catch (error) {
        const errorMsg = error instanceof Error ? error.message : String(error);
        console.error('Error sending email', { error: errorMsg, subject, recipients });
        return { success: false, error: errorMsg };
    }
}
