import { type UseMutationOptions, useMutation } from 'react-query';

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

import useGeneralError from 'src/hooks/useGeneralError';
import { type RequestError, type RequestSuccess } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { duplicateArticle } from '../services';
import { type Article, type DuplicateArticlePayload } from '../types';
import { invalidateSidebarArticles } from '../utils';

type TSuccess = RequestSuccess<typeof duplicateArticle>;
type TError = RequestError;
type TVariables = DuplicateArticlePayload;
type TOptions = UseMutationOptions<TSuccess, TError, TVariables>;

export const useDuplicateArticle = (
  article?: Article,
  options: TOptions = {},
) => {
  const { t } = useLokaliseTranslation('libraries');
  const { enqueueSnackbar } = useSnackbar();
  const showGeneralError = useGeneralError();

  return useMutation<TSuccess, TError, TVariables>({
    mutationFn: payload => {
      if (!article) {
        throw new Error('[useDuplicateArticle] Article is required');
      }
      return duplicateArticle(article.id, payload);
    },
    ...options,
    onSuccess: (...args) => {
      options.onSuccess?.(...args);
      enqueueSnackbar({
        title: t('article.duplicate.success'),
        variant: 'success',
      });
      invalidateSidebarArticles(article?.parentId ?? undefined);
    },
    onError: (err, ...args) => {
      options.onError?.(err, ...args);
      showGeneralError(err);
    },
  });
};
