import { io, Socket } from "socket.io-client";

let socket: Socket | null = null;
let currentUserKey: string | null = null;

// Initialize / get singleton socket.io client instance for a specific user
// Backend expects user identifier in the format: user:${userId}
// and JWT token in auth.token.
export function initSocket(userId: string, token?: string) {
  // Only run in browser
  if (typeof window === "undefined") return null;
  if (!userId) return null;

  const userKey = `user:${userId}`;

  // Reuse existing socket if already initialized for this user
  if (socket && currentUserKey === userKey) {
    return socket;
  }

  currentUserKey = userKey;

  const baseUrl = process.env.NEXT_PUBLIC_API_URL || window.location.origin;

  socket = io(baseUrl, {
    path: "/socket.io",
    transports: ["websocket"],
    autoConnect: true,
    withCredentials: true,
    query: {
      user: userKey,
    },
    auth: token ? { token } : undefined,
  });

  socket.on("connect", () => {
    // Guard for TypeScript: socket is a shared nullable variable
    if (!socket) return;
    // eslint-disable-next-line no-console
    console.log("[socket] connected", socket.id);
  });

  socket.on("connect_error", (err) => {
    // eslint-disable-next-line no-console
    console.error("[socket] connect_error", err?.message || err);
  });

  return socket;
}

// Simple getter (may be null if not initialized)
export function getSocket() {
  return socket;
}
