import io from 'socket.io-client';
import Socket = SocketIOClient.Socket;
let socket: Socket | null = null;
function initializeSocket(token: string): Socket | null {
  if (!socket && token) {
    socket = io({
      auth: { token },
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000,
    });

    socket.on('connect', () => console.log('connected'));

    socket.on('disconnect', () => {
      console.log('Disconnected from server');
    });
  } else if (!socket) {
    console.error('Socket not initialized');
  }
  return socket;
}

async function joinRoom(
  conversation_id: string,
): Promise<{ success: boolean; message: string }> {
  console.log('Attempting to join room:', conversation_id);

  if (!socket) {
    return {
      success: false,
      message: 'Socket connection not available',
    };
  }

  return new Promise((resolve) => {
    socket!.emit(
      'join room',
      conversation_id,
      (response: { status: 'ok' | 'error'; message: string }) => {
        if (response.status === 'ok') {
          console.log('Successfully joined room:', response.message);
          resolve({
            success: true,
            message: response.message,
          });
        } else {
          console.error('Failed to join room:', response.message);
          resolve({
            success: false,
            message: response.message,
          });
        }
      },
    );
  });
}
export { initializeSocket, joinRoom, socket };
