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

// CREATE
export const createEmailConfig = async (req, res) => {
	try {
		const {name, email, type, isActive} = req.body;

		if (!name || !email || !type) {
			return res.status(400).json({
				success: false,
				message: "Name, Email and Type are required",
			});
		}

		const newEmail = await prisma.emailConfig.create({
			data: {
				name,
				email,
				type,
				isActive: isActive ?? true,
			},
		});

		res.status(201).json({
			success: true,
			message: "Email config created",
			data: newEmail,
		});
	} catch (error) {
		console.error(error);
		res.status(500).json({
			success: false,
			message: "Failed to create email config",
		});
	}
};

//GET ALL
export const getEmailConfigs = async (req, res) => {
	try {
		const emails = await prisma.emailConfig.findMany({
			orderBy: {
				createdAt: "desc",
			},
		});

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

// GET SINGLE
export const getEmailConfig = async (req, res) => {
	try {
		const {id} = req.params;

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

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

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

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

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

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

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

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

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