tengo este codigo New private message: adsad from user: bierhffor09 to recipient: [object Object]
Recipient socket ID: undefined  import { Server } from 'socket.io';
import Message from './models/messageModels.js';
import Group from './models/groupModels.js ';
import User from './models/userModels.js';

const getUserById = async (userId) => {
  try {
    const user = await User.findById(userId).select('name city');
    return user;
  } catch (error) {
    console.error(error);
    return null;
  }
};

const getGroupById = async (groupId) => {
  try {
    const group = await Group.findById(groupId).populate('members');
    return group;
  } catch (error) {
    console.error(error);
    return null;
  }
};

const getAllGroups = async () => {
  try {
    const groups = await Group.find({}).populate('members');
    return groups;
  } catch (error) {
    console.error(error);
    return [];
  }
};

const getMessages = async (isPrivate, recipient, group) => {
  try {
    const query = { isPrivate };

    if (recipient) {
      query.recipient = recipient;
    }

    if (group) {
      query.group = group;
    }

    const messages = await Message.find(query).populate('user', 'name city');
    return messages;
  } catch (error) {
    console.error(error);
    return [];
  }
};

const getGroupMessages = async (groupId) => {
  try {
    const messages = await Message.find({ group: groupId }).populate('user', 'name city');
    return messages;
  } catch (error) {
    console.error(error);
    return [];
  }
};

const onlineUsers = new Set();
const connectedUsers = new Map();
const userIdToSocket = new Map();
const userIdToSocketId = new Map(); // Agregado

const updateUserList = (io) => {
  const userList = Array.from(onlineUsers, (id) => connectedUsers.get(id));
  io.emit('online-users', userList);
};

let io;
const socketServer = (server, ioOptions) => {
  io = new Server(server, {
    ...ioOptions,
    cors: {
      origin: '*',
      methods: ['GET', 'POST'],
      allowedHeaders: ['Content-Type', 'Authorization'],
      credentials: true,
    },
  });

  io.on('connection', (socket) => {
    console.log('A client has connected');

    socket.on('chat-message', async ({ text, user }) => {
      console.log(`New message: ${text} from user: ${user.name}`);

      const message = new Message({ text, user: user._id, isPrivate: false });
      await message.save();

      const userDetails = await getUserById(user._id);
      io.emit('chat-message', { ...message._doc, user: userDetails });
    });

    socket.on('private-message', async ({ text, user, recipient }) => {
        console.log(`New private message: ${text} from user: ${user.name} to recipient: ${recipient}`);
      
        const userDetails = await getUserById(user._id);
      
   
        const message = new Message({ text, user: user._id, isPrivate: true, recipient: recipient._id });
        await message.save();
    
        const recipientDetails = await getUserById(recipient._id);
    
        // Emit to the recipient
        const recipientSocketId = userIdToSocketId.get(recipient._id);
        console.log('Recipient socket ID:', recipientSocketId);
        io.to(recipientSocketId).emit('private-message', {
          ...message._doc,
          user: userDetails,
          recipient: recipient._id,
        });
        // Emit to the sender
        socket.emit('private-message', {
            ...message._doc,
            user: userDetails,
            recipient: recipient._id,
            });
    });
    socket.on('request-messages', async (isPrivate, recipient, group) => {
        const messages = await getMessages(isPrivate, recipient, group);
        socket.emit('messages', messages);
      });

    
    socket.on('request-groups', async () => {
      const groups = await getAllGroups();
      socket.emit('groups', groups);
    });


    socket.on('create-group', async ({ name, user }) => {
      console.log(`New group: ${name} created by user: ${user.name}`);
      const newGroup = new Group({ name, members: [user] });
      await newGroup.save();
      const groupDetails = await getGroupById(newGroup._id);
      groupDetails.members.forEach((user) => {
        socket.to(userIdToSocketId.get(user._id)).emit('group-created', groupDetails);
      });
    });

    socket.on('join-group', async ({ group, user }) => {
      console.log(`User: ${user} joined group: ${group}`);
      const groupDetails = await getGroupById(group);
      if (!groupDetails) {
        console.error(`Group not found with ID: ${group}`);
        return;
      }
      groupDetails.members.push(user);
      await groupDetails.save();

      groupDetails.members.forEach((user) => {
        socket.to(userIdToSocketId.get(user._id)).emit('group-joined', groupDetails);
      });
    });

    socket.on('group-message', async ({ text, user, group }) => {
      console.log(`New group message: ${text} from user: ${user.name} to group: ${group}`);

      const userDetails = await getUserById(user._id);
      const message = new Message({ text, user: user._id, isPrivate: false, group });
      await message.save();

      const groupDetails = await getGroupById(group);
      if (!groupDetails) {
        console.error(`Group not found with ID: ${group}`);
        return;
      }
      groupDetails.members.forEach((user) => {
        socket.to(userIdToSocketId.get(user._id)).emit('group-message', {
          ...message._doc,
          user: userDetails,
          group,
        });
      });
    });

    socket.on('request-group-messages', async (groupId) => {
      try {
        const groupMessages = await getGroupMessages(groupId);
        socket.emit('group-messages', groupMessages);
      } catch (error) {
        console.error(`Error al obtener los mensajes del grupo: ${error}`);
      }
    });

    socket.on('user-connected', async (userId) => {
      console.log(`User connected: ${userId}`);
      
      const user = await getUserById(userId);
      onlineUsers.add(userId);
      connectedUsers.set(userId, user);
      userIdToSocket.set(userId, socket);
      console.log('User connected:', JSON.stringify(user));
      userIdToSocketId.set(user._id, socket.id); // Agregado
      updateUserList(io);
    });

    socket.on('user-disconnected', (userId) => {
      console.log(`User disconnected: ${userId}`);
      onlineUsers.delete(userId);
      connectedUsers.delete(userId);
      userIdToSocket.delete(userId);
      console.log('User connected:', JSON.stringify(user));
      userIdToSocketId.delete(user._id);
      updateUserList(io);
    });

    socket.on('disconnect', () => {
      console.log('A client has disconnected');
      const userId = [...userIdToSocket.entries()].find(([, value]) => value === socket)?.[0];
      if (userId) {
        onlineUsers.delete(userId);
        connectedUsers.delete(userId);
        userIdToSocket.delete(userId);
        userIdToSocketId.delete(userId); // Agregado
        updateUserList(io);
      }
    });

    socket.on('request-messages', async (isPrivate, recipient, group) => {
      const messages = await getMessages(isPrivate, recipient, group);
      socket.emit('messages', messages);
    });
  });
};

export { io, socketServer as default };