import { useQuery } from 'react-query';

import { adaptFromChildrenTree } from '@material-hu/components/composed-components/LibrariesSidebar/utils/adapters';

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

export const useGetArticleChildrenTree = (articleId?: number) => {
  return useQuery({
    queryKey: librariesKeys.article.childrenTree(articleId),
    queryFn: () => {
      if (!articleId) {
        throw new Error('[useGetArticleChildrenTree] Article ID is required');
      }
      return getArticleChildrenTree(articleId);
    },
    select: response => adaptFromChildrenTree(response.data, articleId),
    enabled: !!articleId,
    staleTime: CACHE_STALE_TIME,
  });
};
