import { API_URL } from '@game/const';
import { useQuery } from '@tanstack/react-query';
import type { BestServerResponse } from '@api/types';
import { useMemo } from 'react';

export function useBestServer() {
  return useQuery<BestServerResponse>(['best-server'], () => {
    return fetch(`${API_URL}/servers/best`).then((response) => response.json());
  });
}

export function useServerUrl() {
  const bestServerQuery = useBestServer();

  const { isSuccess, data } = bestServerQuery;

  const serverUrl = useMemo(() => {
    if (!isSuccess || !data?.host) {
      return undefined;
    }

    const { host } = data;

    return `ws://${host}`;
  }, [data, isSuccess]);

  return {
    ...bestServerQuery,
    serverUrl
  };
}
