import nodemailer from "nodemailer"
import {secrets} from "./secrets"

export let transporter = null
export const initMailer = async () => {
    transporter = nodemailer.createTransport({
        host: secrets.MAILER_SMTP_HOST,
        port: Number(secrets.MAILER_SMTP_PORT) || 587,
        secure: secrets.MAILER_SMTP_SSL === "true", // true für 465, false für andere Ports
        auth: {
            user: secrets.MAILER_SMTP_USER,
            pass: secrets.MAILER_SMTP_PASS,
        },
    })
    console.log("Mailer Initialized!")
}

export async function sendMail(
    to: string,
    subject: string,
    html: string
): Promise<{ success: boolean; info?: any; error?: any }> {
    try {
        const info = await transporter.sendMail({
            from: secrets.MAILER_FROM,
            to,
            subject,
            html,
        })

        // Nodemailer liefert eine Info-Response zurück
        return { success: true, info }
    } catch (err) {
        console.error("❌ Fehler beim Mailversand:", err)
        return { success: false, error: err }
    }
}