import { useQuery } from 'react-query';

import { CACHE_STALE_TIME } from '../constants';
import { librariesKeys } from '../queries';
import { getArticleTree } from '../services';

export const useGetArticleTree = (
  articleId: number | undefined,
  options?: { enabled?: boolean },
) => {
  return useQuery({
    queryKey: librariesKeys.article.tree(articleId),
    queryFn: () => {
      if (!articleId) {
        throw new Error('[useGetArticleTree] Article ID is required');
      }
      return getArticleTree(articleId);
    },
    select: response => response.data,
    enabled: !!articleId && (options?.enabled ?? true),
    staleTime: CACHE_STALE_TIME,
  });
};
