import { useMutation } from 'react-query';

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

import { queryClient } from 'src/config/react-query';
import { type RequestError, type RequestSuccess } from 'src/types/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { learningCertificatesKeys } from '../queries';
import { createLearningCertificate } from '../services';
import { type CreateLearningCertificateRequest } from '../types';

export type TSuccess = RequestSuccess<typeof createLearningCertificate>;
export type TError = RequestError;
export type TValues = CreateLearningCertificateRequest;

/** Creates the certificate as an inactive draft and returns it with its id. */
export const useCreateLearningCertificate = () => {
  const { enqueueSnackbar } = useSnackbar();
  const { t } = useLokaliseTranslation('learning');

  return useMutation<TSuccess, TError, TValues>({
    mutationFn: createLearningCertificate,
    onError: () => {
      enqueueSnackbar({
        title: t('general:error_title'),
        description: t('general:retry_later'),
        variant: 'error',
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries(learningCertificatesKeys.list.all());
    },
  });
};
