import { Event, User } from "@repo/db";
import nodemailer from "nodemailer";
import { renderCourseCompleted } from "./mail-templates/CourseCompleted";
import { renderPasswordChanged } from "./mail-templates/PasswordChanged";
import { renderVerificationCode } from "./mail-templates/ConfirmEmail";
import { renderBannNotice } from "modules/mail-templates/Bann";
import { renderTimeBanNotice } from "modules/mail-templates/TimeBann";

let transporter: nodemailer.Transporter | null = null;

const initTransporter = () => {
	if (!process.env.MAIL_SERVER) return console.error("MAIL_SERVER is not defined");
	if (!process.env.MAIL_PORT) return console.error("MAIL_PORT is not defined");
	if (!process.env.MAIL_USER) return console.error("MAIL_USER is not defined");
	if (!process.env.MAIL_PASSWORD) return console.error("MAIL_PASSWORD is not defined");

	transporter = nodemailer.createTransport({
		host: process.env.MAIL_SERVER,
		port: parseInt(process.env.MAIL_PORT),
		secure: process.env.MAIL_SECURE === "true", // true for 465, false for other ports
		auth: {
			user: process.env.MAIL_USER,
			pass: process.env.MAIL_PASSWORD,
		},
	});
	transporter.on("error", (err) => {
		console.error("Mail occurred:", err);
	});
	transporter.on("idle", () => {
		console.log("Mail Idle");
	});
};

initTransporter();

export const sendCourseCompletedEmail = async (to: string, user: User, event: Event) => {
	try {
		const emailHtml = await renderCourseCompleted({ user, event });

		if (!transporter) {
			console.error("Transporter is not initialized");
			return;
		}
		await sendMail(to, `Kurs ${event.name} erfolgreich abgeschlossen`, emailHtml);
	} catch (error) {
		console.error("Error sending course completed email:", error);
	}
};

export const sendPasswordChanged = async (to: string, user: User, password: string) => {
	try {
		const emailHtml = await renderPasswordChanged({ user, password });

		await sendMail(to, `Dein Passwort wurde geändert`, emailHtml);
	} catch (error) {}
};

export const sendEmailVerification = async (to: string, user: User, code: string) => {
	try {
		const emailHtml = await renderVerificationCode({
			user,
			code,
		});
		await sendMail(to, "Bestätige deine E-Mail-Adresse", emailHtml);
	} catch (error) {
		console.error("Error sending email verification:", error);
	}
};

export const sendBannEmail = async (to: string, user: User, staffName: string) => {
	try {
		const emailHtml = await renderBannNotice({
			user,
			staffName,
		});
		await sendMail(to, "Deine Sperrung bei Virtual Air Rescue", emailHtml);
	} catch (error) {
		console.error("Error sending ban email:", error);
	}
};

export const sendTimebannEmail = async (to: string, user: User, staffName: string) => {
	try {
		const emailHtml = await renderTimeBanNotice({
			user,
			staffName,
		});
		await sendMail(to, "Deine vorrübergehende Sperrung bei Virtual Air Rescue", emailHtml);
	} catch (error) {
		console.error("Error sending time ban email:", error);
	}
};

export const sendMail = async (to: string, subject: string, html: string) =>
	new Promise<void>(async (resolve, reject) => {
		if (!transporter) {
			console.error("Transporter is not initialized");
			return;
		}
		await transporter.sendMail(
			{
				from: process.env.MAIL_USER,
				to,
				subject: subject,
				html,
			},
			(error, info) => {
				if (error) {
					reject(error);
					console.error("Error sending email:", error);
				} else {
					resolve();
				}
			},
		);
	});
