import fs from "fs";
import nodemailer from "nodemailer";

let transporter = nodemailer.createTransport({
    host: process.env.DSQL_MAIL_HOST,
    port: 465,
    secure: true,
    auth: {
        user: process.env.DSQL_MAIL_EMAIL,
        pass: process.env.DSQL_MAIL_PASSWORD,
    },
});

type Param = {
    to?: string;
    subject?: string;
    text?: string;
    html?: string;
    senderName?: string;
    alias?: string | null;
};

/**
 * # Handle mails With Nodemailer
 */
export default async function handleNodemailer({
    to,
    subject,
    text,
    html,
    alias,
    senderName,
}: Param): Promise<any> {
    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////

    if (
        !process.env.DSQL_MAIL_HOST ||
        !process.env.DSQL_MAIL_EMAIL ||
        !process.env.DSQL_MAIL_PASSWORD
    ) {
        return null;
    }

    const sender = (() => {
        if (alias?.match(/support/i)) return process.env.DSQL_MAIL_EMAIL;
        return process.env.DSQL_MAIL_EMAIL;
    })();

    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////

    let sentMessage;

    if (!fs.existsSync("./email/index.html")) {
        return;
    }

    let mailRoot = fs.readFileSync("./email/index.html", "utf8");
    let finalHtml = mailRoot
        .replace(/{{email_body}}/, html ? html : "")
        .replace(/{{issue_date}}/, Date().substring(0, 24));

    ////////////////////////////////////////
    ////////////////////////////////////////
    ////////////////////////////////////////

    try {
        let mailObject: any = {};

        mailObject["from"] = `"${senderName || "Datasquirel"}" <${sender}>`;
        mailObject["sender"] = sender;
        if (alias) mailObject["replyTo"] = sender;
        mailObject["to"] = to;
        mailObject["subject"] = subject;
        mailObject["text"] = text;
        mailObject["html"] = finalHtml;

        // send mail with defined transport object
        let info = await transporter.sendMail(mailObject);

        sentMessage = info;

        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////
    } catch (/** @type {any} */ error: any) {
        ////////////////////////////////////////
        ////////////////////////////////////////
        ////////////////////////////////////////

        console.log("ERROR in handleNodemailer Function =>", error.message);
        // serverError({
        //     component: "handleNodemailer",
        //     message: error.message,
        //     user: { email: to },
        // });
    }

    return sentMessage;
}
