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

let socket: Socket | null = null;

/**
 * Get the base URL for socket.io connection
 * Uses VITE_BASE_URL if available, otherwise derives from VITE_API_BASE_URL
 */
export function getSocketBaseUrl(): string {
  // Prefer VITE_BASE_URL (direct backend URL without /api/v1)
  const baseUrl = import.meta.env.VITE_BASE_URL;
  if (baseUrl) {
    return baseUrl;
  }

  // Fallback: derive from VITE_API_BASE_URL by removing /api/v1
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
  if (apiBaseUrl) {
    return apiBaseUrl.replace(/\/api\/v1\/?$/, '');
  }

  // Dev fallback
  return '';
}

export function getSocket(baseUrl?: string): Socket {
  // Use provided baseUrl or get from environment
  const url = baseUrl || getSocketBaseUrl();
  if (socket) return socket;

  socket = io(url, {
    withCredentials: true,
    transports: ['websocket', 'polling'],
    path: '/socket.io',
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionAttempts: 5
  });

  socket.on('connect', () => {
    // Socket connected
  });

  socket.on('connect_error', (error) => {
    console.error('[Socket] Connection error:', error.message);
  });

  socket.on('disconnect', (_reason) => {
    // Socket disconnected
  });

  return socket;
}

export function joinRequestRoom(socket: Socket, requestId: string, userId?: string) {
  if (userId) {
    socket.emit('join:request', { requestId, userId });
  } else {
    socket.emit('join:request', requestId);
  }
}

export function leaveRequestRoom(socket: Socket, requestId: string) {
  socket.emit('leave:request', requestId);
}

export function joinUserRoom(socket: Socket, userId: string) {
  socket.emit('join:user', { userId });
}


