import { useQueryClient } from "@tanstack/react-query";
import { useEffect } from "react";
import { ConnectionState } from "~/lib/websocket/gateway/types";
import { useGatewayStore } from "~/stores/gateway-store";
import { useTokenStore } from "~/stores/token-store";

export function GatewayWebSocketConnectionManager() {
    const token = useTokenStore((state) => state.token);

    const { setQueryClient } = useGatewayStore();

    const queryClient = useQueryClient();
    useEffect(() => {
        setQueryClient(queryClient);
    }, [queryClient]);

    useEffect(() => {
        const { status, connect, disconnect } = useGatewayStore.getState();

        if (!!token) {
            connect(token);
        } else {
            if (status === ConnectionState.CONNECTED) {
                disconnect();
            }
        }

        return () => {
            if (status === ConnectionState.CONNECTED) {
                disconnect();
            }
        };
    }, [token]);

    return null;
}
