import { prisma } from "@repo/db";
import { Embed, EmbedBuilder } from "discord.js";
import { Router } from "express";
import client from "modules/discord";

if (!process.env.DISCORD_REPORT_CHANNEL)
	throw new Error("DISCORD_REPORT_CHANNEL environment variable is not set.");

const router: Router = Router();

router.post("/admin-embed", async (req, res) => {
	try {
		const { reportId } = req.body;
		if (!reportId) {
			res.status(400).json({ error: "reportId is required" });
			return;
		}
		const report = await prisma.report.findUnique({
			where: {
				id: Number(reportId),
			},
			include: {
				Reported: true,
				Sender: true,
			},
		});

		if (!report) {
			res.status(404).json({ error: "Report not found" });
			return;
		}

		const embed = new EmbedBuilder()
			.setTitle(`Report #${report.id}`)
			.setURL(`${process.env.NEXT_PUBLIC_HUB_URL}/admin/report/${report.id}`)
			.setDescription(report.text)
			.addFields(
				{
					name: "gemeldeter Nutzer",
					value: `${report.Reported?.firstname} ${report.Reported?.lastname} (${report.Reported?.publicId})`,
					inline: true,
				},
				{ name: "angemeldet als", value: report.reportedUserRole, inline: true },
				{
					name: "gemeldet von",
					value: `${report.Sender?.firstname} ${report.Sender?.lastname} (${report.Sender?.publicId})`,
				},
			)
			.setFooter({
				text: "Bitte reagiere mit 🫡, wenn du den Report bearbeitet hast, oder mit ✅, wenn er abgeschlossen ist.",
			})
			.setTimestamp(new Date(report.timestamp))
			.setColor("DarkRed");

		const reportsChannel = await client.channels.fetch(process.env.DISCORD_REPORT_CHANNEL!);
		if (!reportsChannel || !reportsChannel.isSendable()) {
			res.status(500).json({ error: "Reports channel not found or is not a text channel" });
			return;
		}
		const message = await reportsChannel.send({ embeds: [embed] });
		message.react("🫡").catch(console.error);
		message.react("✅").catch(console.error);
		res.json({
			message: "Report embed sent to Discord channel",
		});
	} catch (error) {
		console.error("Error sending report embed:", error);
		res.status(500).json({ error: "Failed to send report embed" });
	}
});

export default router;
