import { AdminMessage, getPublicUser, Prisma, prisma } from "@repo/db";
import { Router } from "express";
import { io } from "index";
import { renameMember } from "modules/discord";
import { pubClient } from "modules/redis";

const router: Router = Router();

router.get("/", async (req, res) => {
	const user = await prisma.connectedDispatcher.findMany({
		where: {
			logoutTime: null,
		},
	});

	res.json(user);
});

router.patch("/:id", async (req, res) => {
	const { id } = req.params;
	const disaptcherUpdate = req.body as Prisma.ConnectedDispatcherUpdateInput;

	const newDispatcher = await prisma.connectedDispatcher.update({
		where: { id: Number(id) },
		data: {
			...disaptcherUpdate,
		},
		include: { user: true },
	});

	const discordAccount = await prisma.discordAccount.findFirst({
		where: {
			userId: newDispatcher.userId,
		},
	});

	if (discordAccount?.id && !disaptcherUpdate.ghostMode) {
		await renameMember(
			discordAccount.discordId.toString(),
			`${getPublicUser(newDispatcher.user).fullName} • ${newDispatcher.zone}`,
		);
	}

	res.json(newDispatcher);
});

router.delete("/:id", async (req, res) => {
	const { id } = req.params;
	const bann = req.body?.bann as boolean;
	const reason = req.body?.reason as string;
	const until = req.body?.until as Date | null;

	const requiredPermission = bann ? "ADMIN_USER" : "ADMIN_KICK";

	if (!req.user) {
		res.status(401).json({ error: "Unauthorized" });
		return;
	}

	if (!req.user.permissions.includes(requiredPermission)) {
		res.status(403).json({ error: "Forbidden" });
		return;
	}

	try {
		const dispatcher = await prisma.connectedDispatcher.update({
			where: { id: Number(id) },
			data: { logoutTime: new Date() },
			include: { user: true },
		});

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

		const status = bann ? "ban" : "kick";

		io.to(`user:${dispatcher.userId}`).emit("notification", {
			type: "admin-message",
			message: `Du wurdest von ${getPublicUser(req.user).publicId} ${until ? `bis zum ${new Date(until).toLocaleString()} ` : ""} ${
				status === "ban" ? "gekickt, deine Rechte wurden entzogen" : "gekickt"
			}`,
			status,
			data: { admin: getPublicUser(req.user), reason },
		} as AdminMessage);

		io.in(`user:${dispatcher.userId}`).disconnectSockets(true);

		if (bann && !until) {
			await prisma.user.update({
				where: { id: dispatcher.userId },
				data: {
					permissions: {
						set: dispatcher.user.permissions.filter((p) => p !== "DISPO"),
					},
				},
			});
		}
		await prisma.penalty.create({
			data: {
				userId: dispatcher.userId,
				type: bann ? (until ? "TIME_BAN" : "PERMISSIONS_REVOCED") : "KICK",
				until: until ? new Date(until) : new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 50),
				reason: reason,
				createdUserId: req.user.id,
			},
		});

		res.status(204).send();
	} catch (error) {
		console.error(error);
		res.status(500).json({ error: "Failed to disconnect dispatcher" });
	}
});

export default router;
