import { getPublicUser, prisma, User } from "@repo/db";
import { addRolesToMember, removeRolesFromMember, renameMember } from "modules/discord";
import { getNextDateWithTime, getUserPenaltys } from "@repo/shared-components";
import { DISCORD_ROLES } from "@repo/db";
import { Server, Socket } from "socket.io";

export const handleConnectDispatch =
	(socket: Socket, io: Server) =>
	async ({
		logoffTime,
		selectedZone,
		ghostMode,
	}: {
		logoffTime: string;
		selectedZone: string;
		ghostMode: boolean;
	}) => {
		try {
			const user: User = socket.data.user; // User ID aus dem JWT-Token

			if (!user) return Error("User not found");

			if (!user.permissions.includes("DISPO")) {
				socket.emit("connect-message", {
					message: "Fehlende Berechtigung",
				});
				socket.disconnect();
				return;
			}

			const userPenaltys = await getUserPenaltys(user.id);

			if (
				userPenaltys.openTimeban.length > 0 ||
				user.isBanned ||
				userPenaltys.openBans.length > 0
			) {
				socket.emit("connect-message", {
					message: "Du hast eine aktive Strafe und kannst dich deshalb nicht verbinden.",
				});
				socket.disconnect();
				return;
			}

			const existingConnection = await prisma.connectedDispatcher.findFirst({
				where: {
					userId: user.id,
					logoutTime: null,
				},
			});

			if (existingConnection) {
				await io.to(`user:${user.id}`).emit("force-disconnect", "double-connection");
				await prisma.connectedDispatcher.updateMany({
					where: {
						userId: user.id,
						logoutTime: null,
					},
					data: {
						logoutTime: new Date().toISOString(),
					},
				});
			}

			const connectedDispatcherEntry = await prisma.connectedDispatcher.create({
				data: {
					publicUser: getPublicUser(user) as any,
					esimatedLogoutTime: logoffTime.length > 0 ? logoffTime : null,
					lastHeartbeat: new Date().toISOString(),
					userId: user.id,
					zone: selectedZone,
					loginTime: new Date().toISOString(),
					ghostMode,
				},
			});

			const discordAccount = await prisma.discordAccount.findFirst({
				where: {
					userId: user.id,
				},
			});
			if (discordAccount?.id && !ghostMode) {
				await renameMember(
					discordAccount.discordId.toString(),
					`${getPublicUser(user).fullName} • ${selectedZone}`,
				);
				await addRolesToMember(discordAccount.discordId.toString(), [
					DISCORD_ROLES.ONLINE_DISPATCHER,
				]);
			}

			socket.join("dispatchers"); // Dem Dispatcher-Raum beitreten
			socket.join(`user:${user.id}`); // Dem User-Raum beitreten

			io.to(`user:${user.id}`).emit("own-dispatcher", connectedDispatcherEntry);
			io.to("dispatchers").emit("dispatchers-update", connectedDispatcherEntry);
			io.to("pilots").emit("dispatchers-update", connectedDispatcherEntry);

			socket.on("disconnect", async () => {
				await prisma.connectedDispatcher.update({
					where: {
						id: connectedDispatcherEntry.id,
					},
					data: {
						logoutTime: new Date().toISOString(),
					},
				});

				io.to("dispatchers").emit("dispatchers-update");
				io.to("pilots").emit("dispatchers-update");
				if (discordAccount?.id) {
					await renameMember(
						discordAccount.discordId.toString(),
						`${getPublicUser(user).fullName} - ${user.publicId}`,
					);
					await removeRolesFromMember(discordAccount.discordId.toString(), [
						DISCORD_ROLES.ONLINE_DISPATCHER,
					]);
				}
			});
		} catch (error) {
			console.error("Error connecting to dispatch server:", error);
		}
	};
