/** biome-ignore-all lint/correctness/useExhaustiveDependencies: we only want to fetch the article if id changes */
import { useEffect, useState } from 'react';

import useSnackbar from '@material-hu/components/design-system/Snackbar';

import { queryClient } from 'src/config/react-query';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { type Article } from '../types';
import { getCachedArticleById } from '../utils';

import { getArticleQueryOptions } from './useGetArticle';

export const useCachedArticle = (articleId?: number | null) => {
  const { t } = useLokaliseTranslation('libraries');
  const { enqueueSnackbar } = useSnackbar();
  const [article, setArticle] = useState<Article | null>(null);

  useEffect(() => {
    const getArticle = async () => {
      if (!articleId) {
        setArticle(null);
        return;
      }

      let article = getCachedArticleById(articleId);

      if (!article) {
        try {
          const queryOptions = getArticleQueryOptions(articleId);
          const response = await queryClient.fetchQuery(queryOptions);
          article = response.data;
        } catch {
          enqueueSnackbar({ title: t('article.error'), variant: 'error' });
        }
      }

      setArticle(article);
    };

    getArticle();
  }, [articleId, t]);

  return { article };
};
