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

// GET ALL CAREERS

export const getAllCareers = async (req, res) => {
	try {
		const careers = await prisma.career.findMany({
			orderBy: {createdAt: "desc"},
		});

		const response = careers.map((c) => ({
			id: c.id,
			post: c.post,
			designation: c.designation,
			qualification: c.qualification,
			experienceNeed: c.experienceNeed,
			email: c.email,
			number: c.number,
			status: c.status,
		}));

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

// CREATE CAREER

export const createCareer = async (req, res) => {
	try {
		const {
			post,
			designation,
			qualification,
			experienceNeed,
			email,
			number,
			status,
		} = req.body;

		if (!post || !designation) {
			return res.status(400).json({
				success: false,
				message: "Post and designation are required",
			});
		}

		const career = await prisma.career.create({
			data: {
				post,
				designation,
				qualification,
				experienceNeed,
				email,
				number,
				status,
			},
		});

		return res.status(201).json({
			success: true,
			message: "Career created successfully",
			data: career,
		});
	} catch (error) {
		console.error(error);
		return res.status(500).json({
			success: false,
			message: "Failed to create career",
		});
	}
};

// UPDATE CAREER (PATCH)

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

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

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

// DELETE CAREER

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

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

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