import { Server } from "socket.io";

let ioInstance: Server | null = null;

export function setIO(io: Server): void {
  ioInstance = io;
}

export function getIO(): Server | null {
  return ioInstance;
}

function conversationRoom(conversationId: string): string {
  return `conversation:${conversationId}`;
}

/**
 * True if the user has at least one socket joined to this conversation room.
 * Used to skip FCM when the recipient is actively viewing the chat.
 */
export async function isUserInConversation(
  userId: string,
  conversationId: string,
): Promise<boolean> {
  const io = ioInstance;
  if (!io || !userId || !conversationId) return false;
  try {
    const sockets = await io.in(conversationRoom(conversationId)).fetchSockets();
    return sockets.some((s) => String(s.data?.userId ?? "") === userId);
  } catch {
    return false;
  }
}
