import { useQuery } from 'react-query';

import { useAuth } from 'src/contexts/JWTContext';
import { getCompetitions, getProdeAccess, prodeKeys } from 'src/services/prode';

const useCompetitions = () => {
  const { isAuthenticated, isInitialized } = useAuth();

  const { data: accessData, isLoading: isAccessLoading } = useQuery(
    prodeKeys.access(),
    () => getProdeAccess(),
    {
      enabled: isAuthenticated,
      select: res => res.data,
    },
  );

  const { data: competitions, isLoading: isCompetitionsLoading } = useQuery(
    prodeKeys.competitions(),
    () => getCompetitions(),
    {
      enabled: isAuthenticated && !!accessData?.hasAccess,
      select: res => res.data,
    },
  );

  const isLoading = !isInitialized || isAccessLoading || isCompetitionsLoading;
  const isSingleCompetition = !isLoading && competitions?.length === 1;

  return {
    competitions,
    accessData,
    isLoading,
    isSingleCompetition,
  };
};

export default useCompetitions;
