import { prisma } from "@repo/db";
import { pubClient } from "modules/redis";
import { Server, Socket } from "socket.io";

export const handleSendMessage =
	(socket: Socket, io: Server) =>
	async (
		{ userId, message }: { userId: string; message: string },
		cb: (err: { error?: string }) => void,
	) => {
		console.log("send-message", userId, message);
		const senderId = socket.data.user.id;

		const senderUser = await prisma.user.findUnique({
			where: { id: senderId },
		});

		const receiverUser = await prisma.user.findUnique({
			where: { id: userId },
		});

		const dbMessage = await prisma.chatMessage.create({
			data: {
				text: message,
				receiverId: userId,
				senderId,
				receiverName: `${receiverUser?.firstname} ${receiverUser?.lastname[0]}. - ${receiverUser?.publicId}`,
				senderName: `${senderUser?.firstname} ${senderUser?.lastname[0]}. - ${senderUser?.publicId}`,
			},
		});

		io.to(`user:${dbMessage.receiverId}`).emit("chat-message", {
			userId: dbMessage.senderId,
			message: dbMessage,
		});
		io.to(`user:${dbMessage.senderId}`).emit("chat-message", {
			userId: dbMessage.receiverId,
			message: dbMessage,
		});
		const recvSockets = await io.in(`user:${userId}`).fetchSockets();
		await io.in(`user:${senderId}`).fetchSockets();

		if (!recvSockets.length) {
			cb({ error: "User is not connected" });
		} else {
			cb({});
		}
		console.log(`${socket.data.user.publicId} sent message to ${userId}`);
	};
