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

// GET ALL NEWS

export const getAllNews = async (req, res) => {
	try {
		const page = parseInt(req.query.page);
		const limit = parseInt(req.query.limit);

		if (!page && !limit) {
			const news = await prisma.newsMedia.findMany({
				orderBy: { createdAt: "desc" },
			});

			const response = news.map((n) => ({
				Id: n.id.toString(),
				Headline: n.headline,
				Content: n.content,
				FirstPara: n.firstPara,
				SecondPara: n.secondPara,
				Date: n.date,
				Author: n.author,
			}));

			return res.status(200).json({
				success: true,
				data: response,
				meta: null,
			});
		}

		const currentPage = page || 1;
		const currentLimit = limit || 10;

		const skip = (currentPage - 1) * currentLimit;

		const [news, total] = await Promise.all([
			prisma.newsMedia.findMany({
				orderBy: { createdAt: "desc" },
				skip,
				take: currentLimit,
			}),
			prisma.newsMedia.count(),
		]);

		const response = news.map((n) => ({
			Id: n.id.toString(),
			Headline: n.headline,
			Content: n.content,
			FirstPara: n.firstPara,
			SecondPara: n.secondPara,
			Date: n.date,
			Author: n.author,
		}));

		return res.status(200).json({
			success: true,
			data: response,
			meta: {
				total,
				page: currentPage,
				limit: currentLimit,
				totalPages: Math.ceil(total / currentLimit),
			},
		});
	} catch (error) {
		console.error(error);
		return res.status(500).json({
			success: false,
			message: "Failed to fetch news",
		});
	}
};

// GET NEWS BY ID

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

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

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

		const response = {
			Id: n.id.toString(),
			Headline: n.headline,
			Content: n.content,
			FirstPara: n.firstPara,
			SecondPara: n.secondPara,
			Date: n.date,
			Author: n.author,
		};

		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 news",
		});
	}
};

// CREATE NEWS

export const createNews = async (req, res) => {
	try {
		const { headline, content, firstPara, secondPara, date, author } = req.body;

		if (!headline) {
			return res.status(400).json({
				success: false,
				message: "Headline is required",
			});
		}

		const news = await prisma.newsMedia.create({
			data: {
				headline,
				content,
				firstPara,
				secondPara,
				date: date ? new Date(date) : null,
				author,
			},
		});

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

// UPDATE NEWS

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

		const news = await prisma.newsMedia.update({
			where: { id: Number(id) },
			data: {
				...req.body,
				date: req.body.date ? new Date(req.body.date) : undefined,
			},
		});

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

// DELETE NEWS

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

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

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