import { useQuery } from 'react-query';

import useGeneralError from 'src/hooks/useGeneralError';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

export const getArticleQueryOptions = (articleId?: number) => ({
  queryKey: librariesKeys.article.byId(articleId),
  queryFn: () => {
    if (!articleId) throw new Error('[useGetArticle] Article ID is required');
    return getArticle(articleId);
  },
});

export const useGetArticle = (articleId?: number) => {
  const { t } = useLokaliseTranslation('libraries');
  const showGeneralError = useGeneralError();

  return useQuery({
    ...getArticleQueryOptions(articleId),
    enabled: !!articleId,
    select: response => response.data,
    onError: err => showGeneralError(err, t('article.error')),
    staleTime: CACHE_STALE_TIME,
  });
};
