import path from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import type { Transporter } from "nodemailer";
import nodemailer from "nodemailer";
import type Mail from "nodemailer/lib/mailer/index.js";
import hbs from "nodemailer-express-handlebars";
import { returnFunc } from "./returnHelper.utils.js";
import { tryCatch } from "./trycatch.utils.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) => {
	const fromEmail: string = `DoNotReply@mail.alpla.com`;
	const transporter: Transporter = nodemailer.createTransport({
		host: "smtp.azurecomm.net",
		port: 587,
		//rejectUnauthorized: false,
		tls: {
			minVersion: "TLSv1.2",
		},
		auth: {
			user: "donotreply@mail.alpla.com",
			pass: process.env.SMTP_PASSWORD,
		},
		debug: true,
	});

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

	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);

	const { data: mail, error } = await tryCatch(sendMailPromise(mailOptions));

	if (mail) {
		return returnFunc({
			success: true,
			level: "info",
			module: "utils",
			subModule: "sendmail",
			message: `Email was sent to: ${data.email}`,
			data: [],
			notify: false,
		});
	}

	if (error) {
		return returnFunc({
			success: false,
			level: "error",
			module: "utils",
			subModule: "sendmail",
			message: `Error sending Email to : ${data.email}, Error: ${error.message}`,
			data: [{ error: error }],
			notify: false,
		});
	}
};
