import prisma from "../prisma/client.js";
import { sendEmail } from "../utils/sendEmail.js";
import { getEmailsByType } from "../utils/getEmailByTypes.js";

// CREATE ACADEMICS & RESEARCH

export const createAcademicsResearch = async (req, res) => {
	try {
		const { fullName, number, emailId, subject, courseName, message } =
			req.body;

		if (!fullName || !number) {
			return res.status(400).json({
				success: false,
				message: "Full name and number are required",
			});
		}

		const data = await prisma.academicsResearch.create({
			data: {
				fullName,
				number,
				emailId,
				subject,
				courseName,
				message,
			},
		});

		try {
			const emailList = await getEmailsByType("ACADEMICS");

			if (emailList && emailList.length > 0) {
				await sendEmail({
					to: emailList,
					subject: "New Academics & Research Inquiry",
					html: `
						<h2>New Academics & Research Inquiry</h2>

						<p><b>Name:</b> ${fullName}</p>
						<p><b>Phone:</b> ${number}</p>
						<p><b>Email:</b> ${emailId || "-"}</p>

						<p><b>Course:</b> ${courseName || "-"}</p>
						<p><b>Subject:</b> ${subject || "-"}</p>

						<p><b>Message:</b></p>
						<p>${message || "-"}</p>
					`,
				});
			}
		} catch (err) {
			console.error("Academics email failed:", err);
		}

		res.status(200).json({
			success: true,
			status: 200,
			data,
			message: "Academics & Research added successfully",
		});
	} catch (error) {
		console.error(error);
		res.status(500).json({
			success: false,
			message: "Failed to add Academics & Research inquiry",
		});
	}
};

// GET ALL

export const getAcademicsResearch = async (req, res) => {
	try {
		const data = await prisma.academicsResearch.findMany({
			orderBy: {
				createdAt: "desc",
			},
		});

		res.json({
			success: true,
			data,
		});
	} catch (error) {
		res.status(500).json({
			success: false,
			message: "Failed to fetch records",
		});
	}
};

// GET SINGLE

export const getSingleAcademicsResearch = async (req, res) => {
	try {
		const { id } = req.params;

		const data = await prisma.academicsResearch.findUnique({
			where: {
				id: Number(id),
			},
		});

		if (!data) {
			return res.status(404).json({
				success: false,
				message: "Record not found",
			});
		}

		res.json({
			success: true,
			data,
		});
	} catch (error) {
		res.status(500).json({
			success: false,
			message: "Failed to fetch record",
		});
	}
};

// DELETE

export const deleteAcademicsResearch = async (req, res) => {
	try {
		const { id } = req.params;

		await prisma.academicsResearch.delete({
			where: {
				id: Number(id),
			},
		});

		res.json({
			success: true,
			message: "Record deleted successfully",
		});
	} catch (error) {
		res.status(500).json({
			success: false,
			message: "Failed to delete record",
		});
	}
};
