import { AdminMessage, getPublicUser, Prisma, prisma } from "@repo/db";
import { Router } from "express";
import { io } from "index";
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,
		},
	});

	res.json(newDispatcher);
});

import { Request, Response } from "express";

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

	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: bann ? { user: true } : undefined,
		});

		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: "Verbindung durch einen Administrator getrennt",
			status,
			data: { admin: getPublicUser(req.user) },
		} as AdminMessage);

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

		if (bann) {
			await prisma.user.update({
				where: { id: dispatcher.userId },
				data: {
					permissions: {
						set: req.user.permissions.filter((p) => p !== "DISPO"),
					},
				},
			});
		}

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

export default router;
