import prisma from "../prisma/client.js";

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

// CREATE CANDIDATE

export const createCandidate = async (req, res) => {
	try {
		const { fullName, mobile, email, subject, coverLetter, careerId } =
			req.body;

		if (!fullName || !mobile || !email || !careerId) {
			return res.status(400).json({
				success: false,
				message: "Required fields missing",
			});
		}

		const candidate = await prisma.candidate.create({
			data: {
				fullName,
				mobile,
				email,
				subject,
				coverLetter,
				careerId: Number(careerId),
			},
			include: {
				career: true,
			},
		});

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

			if (emailList && emailList.length > 0) {
				await sendEmail({
					to: emailList,
					subject: "New Job Application Received",
					html: `
						<h2>New Candidate Application</h2>

						<p><b>Name:</b> ${fullName}</p>
						<p><b>Phone:</b> ${mobile}</p>
						<p><b>Email:</b> ${email}</p>

						<p><b>Applied For:</b> ${candidate.career?.post || "-"}</p>
						<p><b>Designation:</b> ${candidate.career?.designation || "-"}</p>

						<p><b>Subject:</b> ${subject || "-"}</p>
						<p><b>Cover Letter:</b></p>
						<p>${coverLetter || "-"}</p>
					`,
				});
			}
		} catch (err) {
			console.error("Candidate email failed:", err);
		}

		res.status(201).json({
			success: true,
			message: "Application submitted successfully",
			data: candidate,
		});
	} catch (error) {
		console.error(error);
		res.status(500).json({
			success: false,
			message: "Failed to create candidate",
		});
	}
};

// GET ALL CANDIDATES

export const getCandidates = async (req, res) => {
	try {
		const candidates = await prisma.candidate.findMany({
			include: {
				career: true,
			},
			orderBy: {
				createdAt: "desc",
			},
		});

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

// GET SINGLE CANDIDATE

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

		const candidate = await prisma.candidate.findUnique({
			where: {
				id: Number(id),
			},
			include: {
				career: true,
			},
		});

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

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

// GET CANDIDATES BY CAREER

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

		const candidates = await prisma.candidate.findMany({
			where: {
				careerId: Number(careerId),
			},
			include: {
				career: true,
			},
			orderBy: {
				createdAt: "desc",
			},
		});

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

// UPDATE CANDIDATE

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

		const candidate = await prisma.candidate.update({
			where: {
				id: Number(id),
			},
			data: req.body,
		});

		res.status(200).json({
			success: true,
			message: "Candidate updated successfully",
			data: candidate,
		});
	} catch (error) {
		console.error(error);
		res.status(500).json({
			success: false,
			message: "Failed to update candidate",
		});
	}
};

// DELETE CANDIDATE

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

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

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