import { useMutation, useQueryClient } from 'react-query';

import { type RequestError, type RequestSuccess } from 'src/types/services';

import { librariesKeys } from '../queries';
import { uploadArticleIcon } from '../services';

type TSuccess = RequestSuccess<typeof uploadArticleIcon>;
type TError = RequestError;
type TValues = { file: File };

export const useUploadArticleIcon = (articleId?: number) => {
  const queryClient = useQueryClient();

  return useMutation<TSuccess, TError, TValues>({
    mutationFn: ({ file }) => {
      if (!articleId)
        throw new Error('[useUploadArticleIcon] Article ID is required');
      return uploadArticleIcon(articleId, file);
    },
    onSuccess: () =>
      queryClient.invalidateQueries(librariesKeys.article.icons(articleId)),
  });
};
