import { Router } from "express";
import { sendEmailVerification, sendMail } from "modules/mail";
import { sendPasswordChanged, sendCourseCompletedEmail } from "modules/mail";

const router: Router = Router();

router.post("/send", async (req, res) => {
	const { to, subject, html } = req.body;

	try {
		await sendMail(to, subject, html);
		// Send email logic here
		res.status(200).json({ message: "Email sent successfully" });
	} catch (error) {
		res.status(500).json({ error: "Failed to send email" });
	}
});

router.post("/template/:template", async (req, res) => {
	const { template } = req.params;
	const { to, data } = req.body;
	if (!to || !data) {
		res.status(400).json({ error: "Missing required fields" });

		return;
	}

	if (!data.user) {
		res.status(400).json({ error: "Missing user data" });
		return;
	}
	console.log("template", template);
	switch (template) {
		case "password-change":
			if (!data.password) {
				res.status(400).json({ error: "Missing password data" });
				return;
			}
			await sendPasswordChanged(to, data.user, data.password);
			break;
		case "course-completed":
			if (!data.event) {
				res.status(400).json({ error: "Missing event data" });
				return;
			}
			await sendCourseCompletedEmail(to, data.user, data.event);
			break;
		case "email-verification":
			if (!data.code) {
				res.status(400).json({ error: "Missing verification code" });
				return;
			}
			await sendEmailVerification(to, data.user, data.code);
		default:
			res.status(400).json({ error: "Invalid template" });
			return;
	}
	res.status(200).json({ message: "Email sent successfully" });
});

export default router;
