import { ref, onMounted, onBeforeUnmount } from "vue";
import {
  connectWebSocket,
  disconnectWebSocket,
  sendEvent,
  sendEventAndWait,
  onEvent,
  isWebSocketConnected,
} from "@/services/ws";

export function useWebSocket() {
  const isConnected = ref(isWebSocketConnected());
  const lastMessage = ref<any>(null);

  const lastError = ref<string | null>(null);

  async function safeConnect(url?: string) {
    return connectWebSocket(url)
      .then(() => {
        isConnected.value = true;
      })
      .catch((err) => {
        lastError.value = err?.message ?? "Unknown WS error";
        throw err;
      });
  }

  function useEvent<T = any>(event: string, handler: (data: T) => void) {
    const wrapped = (data: T) => {
      lastMessage.value = { event, data };
      handler(data);
    };

    onMounted(() => {
      onEvent(event, wrapped);
    });

    onBeforeUnmount(() => {
      onEvent(event, () => {});
    });
  }

  return {
    isConnected,
    lastMessage,
    lastError,

    connect: safeConnect,
    disconnect: disconnectWebSocket,
    send: sendEvent,
    sendAndWait: sendEventAndWait,

    useEvent,
  };
}
