import type { Address } from "nodemailer/lib/mailer/index.js";
import type { Transporter } from "nodemailer";
import type SMTPTransport from "nodemailer/lib/smtp-transport/index.js";
import type Mail from "nodemailer/lib/mailer/index.js";
import os from "os";
import nodemailer from "nodemailer";
import path from "path";
import { fileURLToPath } from "url";
import { promisify } from "util";
import hbs from "nodemailer-express-handlebars";
import { createLogger } from "../../logger/logger.js";

interface HandlebarsMailOptions extends Mail.Options {
    template: string;
    context: Record<string, unknown>;
}

interface EmailData {
    email: string;
    subject: string;
    template: string;
    context: Record<string, unknown>;
}

export const sendEmail = async (data: EmailData): Promise<any> => {
    const log = createLogger({ module: "pkg", subModule: "sendMail" });
    let transporter: Transporter;
    let fromEmail: string | Address;

    if (
        os.hostname().includes("OLP") &&
        process.env.EMAIL_USER &&
        process.env.EMAIL_PASSWORD
    ) {
        transporter = nodemailer.createTransport({
            service: "gmail",
            auth: {
                user: process.env.EMAIL_USER,
                pass: process.env.EMAIL_PASSWORD,
            },
            //debug: true,
        });

        // update the from email
        fromEmail = process.env.EMAIL_USER;
    } else {
        // convert to the correct plant token.

        let host = `${os.hostname().replace("VMS006", "")}-smtp.alpla.net`;

        //const testServers = ["vms036", "VMS036"];

        if (os.hostname().includes("VMS036")) {
            host = "USMCD1-smtp.alpla.net";
        }

        // if (plantToken[0].value === "usiow2") {
        //     host = "USIOW1-smtp.alpla.net";
        // }

        transporter = nodemailer.createTransport({
            host: host,
            port: 25,
            rejectUnauthorized: false,
            //secure: false,
            // auth: {
            //   user: "alplaprod",
            //   pass: "obelix",
            // },
            debug: true,
        } as SMTPTransport.Options);

        // update the from email
        fromEmail = `noreply@alpla.com`;
    }

    // creating the handlbar options
    const viewPath = path.resolve(
        path.dirname(fileURLToPath(import.meta.url)),
        "./views/"
    );

    const handlebarOptions = {
        viewEngine: {
            extname: ".hbs",
            //layoutsDir: path.resolve(viewPath, "layouts"), // Path to layouts directory
            defaultLayout: "", // Specify the default layout
            partialsDir: viewPath,
        },
        viewPath: viewPath,
        extName: ".hbs", // File extension for Handlebars templates
    };

    transporter.use("compile", hbs(handlebarOptions));

    const mailOptions: HandlebarsMailOptions = {
        from: fromEmail,
        to: data.email,
        subject: data.subject,
        //text: "You will have a reset token here and only have 30min to click the link before it expires.",
        //html: emailTemplate("BlakesTest", "This is an example with css"),
        template: data.template, // Name of the Handlebars template (e.g., 'welcome.hbs')
        context: data.context,
    };

    // now verify and send the email
    const sendMailPromise = promisify(transporter.sendMail).bind(transporter);

    try {
        // Send email and await the result
        const info = await sendMailPromise(mailOptions);
        log.info(null, `Email was sent to: ${data.email}`);
        return { success: true, message: "Email sent.", data: info };
    } catch (err) {
        console.log(err);
        log.error(
            { error: err },

            `Error sending Email to : ${data.email}`
        );
        return { success: false, message: "Error sending email.", error: err };
    }
};
