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

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: 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) => {
	const emailHtml = await renderCourseCompleted({ user, event });

	if (!transporter) {
		console.error("Transporter is not initialized");
		return;
	}
	sendMail(to, `Kurs ${event.name} erfolgreich abgeschlossen`, emailHtml);
};

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

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

export const sendEmailVerification = async (to: string, user: User, code: string) => {
	const emailHtml = await renderVerificationCode({
		user,
		code,
	});
	await sendMail(to, "Bestätige deine E-Mail-Adresse", emailHtml);
};

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();
				}
			},
		);
	});
