import { getPublicUser, HpgState, prisma, User } from "@repo/db";
import { Socket, Server } from "socket.io";

interface PTTData {
	shouldTransmit: boolean;
	source: string;
}

export const handleConnectDesktop = (socket: Socket, io: Server) => () => {
	const user = socket.data.user as User;

	socket.join(`user:${user.id}`);
	socket.join(`desktop:${user.id}`);

	socket.on("ptt", async (data: PTTData) => {
		socket.to(`user:${user.id}`).emit("ptt", data);
		const connectedAircraft = await prisma.connectedAircraft.findFirst({
			where: {
				userId: user.id,
				logoutTime: null,
			},
			include: {
				Station: true,
			},
		});

		const connectedDispatcher = await prisma.connectedDispatcher.findFirst({
			where: {
				userId: user.id,
				logoutTime: null,
			},
		});
		const otherPttData = {
			publicUser: getPublicUser(user),
			source:
				connectedAircraft?.Station.bosCallsignShort || connectedDispatcher
					? "Leitstelle"
					: user.publicId,
		};
		if (data.shouldTransmit) {
			socket.to("dispatchers").emit("other-ptt", otherPttData);
			socket.to("pilots").emit("other-ptt", otherPttData);
		}
	});
};
