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 { updateLearningCertificate } from '../services';
import { type UpdateLearningCertificateParams } from '../types';

export type TSuccess = RequestSuccess<typeof updateLearningCertificate>;
export type TError = RequestError;
export type TValues = UpdateLearningCertificateParams;

/**
 * Partially updates a certificate via `PATCH /:id`. Reused both for the design
 * step (color, alignment, signatures, logos) and final activation (status).
 */
export const useUpdateLearningCertificate = () => {
  const { enqueueSnackbar } = useSnackbar();
  const { t } = useLokaliseTranslation('learning');

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