import nodemailer from "nodemailer";
import hbs from "nodemailer-express-handlebars";
import path from "path";

interface MailOptions {
	from: string;
	to: string[];
	subject: string;
	template: string;
	context: object;
}

export function prepareMailer(template?: string): nodemailer.Transporter {
	const transport = nodemailer.createTransport({
		host: process.env.SMTP_HOST,
		auth: {
			user: process.env.MAIL_USER!,
			pass: process.env.MAIL_PASS!,
		},
	});

	const handlebarOptions: hbs.NodemailerExpressHandlebarsOptions = {
		viewEngine: {
			partialsDir: path.resolve("src/email/templates"),
			defaultLayout: `src/email/templates/${template || "main"}`,
		},
		viewPath: path.resolve("src/email/templates"),
	};

	transport.use("compile", hbs(handlebarOptions));
	return transport;
}

export function prepareMailOptions(context: object, to: string[], subject: string, template: string): MailOptions {
	return {
		from: process.env.MAIL_USER!,
		to,
		subject,
		template,
		context,
	};
}

export async function sendEmail(template: string, context: object, to: string[], subject: string): Promise<boolean> {
	try {
		const transport = prepareMailer(template);
		const mailOptions = prepareMailOptions(context, to, subject, template);

		await transport.sendMail(mailOptions);
		return true;
	} catch {
		return false;
	}
}
