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

const SOCKET_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:4000';

export const createSocketClient = (token) => {
  const socket = io(SOCKET_URL, {
    autoConnect: false,
    transports: ['websocket'],
    withCredentials: true,
    auth: { token },
  });

  socket.on('connect_error', (error) => {
    console.warn('[Socket] Bağlantı hatası', error.message);
  });

  socket.on('disconnect', (reason) => {
    console.info('[Socket] Bağlantı koptu', reason);
  });

  socket.on('connection:ready', (payload) => {
    console.info('[Socket] Hazır', payload);
  });

  const connect = () => {
    if (!socket.connected) {
      socket.connect();
    }
  };

  const disconnect = () => {
    if (socket.connected) {
      socket.disconnect();
    }
  };

  const subscribeAdminEvents = (handlers = {}) => {
    const offFns = [];
    const register = (event, fn) => {
      socket.on(event, fn);
      offFns.push(() => socket.off(event, fn));
    };

    if (handlers.onEpubGenerated) {
      register('epub:generated', handlers.onEpubGenerated);
    }
    if (handlers.onEpubFailed) {
      register('epub:failed', handlers.onEpubFailed);
    }
    if (handlers.onTranslateCompleted) {
      register('translate:completed', handlers.onTranslateCompleted);
    }
    if (handlers.onTranslateFailed) {
      register('translate:failed', handlers.onTranslateFailed);
    }
    if (handlers.onStatsUpdate) {
      register('stats:update', handlers.onStatsUpdate);
    }
    if (handlers.onModelChanged) {
      register('translate:model-changed', handlers.onModelChanged);
    }
    if (handlers.onUserRegistered) {
      register('user:registered', handlers.onUserRegistered);
    }
    if (handlers.onPresenceUpdate) {
      register('presence:update', handlers.onPresenceUpdate);
    }

    return () => {
      offFns.forEach((off) => off());
    };
  };

  return {
    socket,
    connect,
    disconnect,
    subscribeAdminEvents,
  };
};

export const ensureSocket = (existingSocket, token) => {
  if (existingSocket) {
    return existingSocket;
  }
  return createSocketClient(token);
};
