// utils/socketManager.js
const userSockets = new Map(); // userId -> socket

const addUserSocket = (userId, socket) => {
  userSockets.set(userId.toString(), socket);
  console.log(`✅ User ${userId} socket stored. Total connections: ${userSockets.size}`);
};

const removeUserSocket = (userId) => {
  userSockets.delete(userId.toString());
  console.log(`❌ User ${userId} socket removed. Total connections: ${userSockets.size}`);
};

const getUserSocket = (userId) => {
  return userSockets.get(userId.toString());
};

const emitToUser = (userId, event, data) => {
  const socket = getUserSocket(userId);
  if (socket) {
    socket.emit(event, data);
    console.log(`📤 Emitted ${event} to user ${userId}`);
    return true;
  }
  console.log(`⚠️  User ${userId} not connected, cannot emit ${event}`);
  return false;
};

module.exports = {
  addUserSocket,
  removeUserSocket,
  getUserSocket,
  emitToUser
};