import { useWebSocketStore } from "@/services";

export const useAudioWebSocket = () => {
  const webSocketStore = useWebSocketStore();

  const sendMessage = (data: string | Uint8Array) => {
    if (webSocketStore.connected) {
      if (typeof data === "string") {
        webSocketStore.send(data);
      } else {
        webSocketStore.websocket?.send(data);
      }
    }
  };

  const ensureConnection = async (): Promise<void> => {
    if (!webSocketStore.connected) {
      webSocketStore.connect();
      await new Promise<void>((resolve) => {
        const check = () => {
          if (webSocketStore.connected) resolve();
          else setTimeout(check, 100);
        };
        check();
      });
    }
  };

  return { sendMessage, ensureConnection };
};
