import { useMutation, useQuery } from '@tanstack/react-query';

import api from '../services/api';
import { showFeedback } from '../services/feedback/showFeedback';

export const useMessages = (token: string, enabled = true) => {
  return useQuery(['message-all', token], () => api.message.messageAllGet(token), {
    enabled: !!token && enabled,
  });
};

export const useMessageDetail = (token: string, messageId: string) => {
  return useQuery(
    ['message-detail', token, messageId],
    () => api.message.messageDetailGet(token, messageId),
    {
      enabled: !!token && !!messageId,
    },
  );
};

export const useMessageDelete = (
  token: string,
  refetchMessages: () => void,
  goBack: () => void,
) => {
  return useMutation(
    ['message-delete', token],
    (messageId: string) => api.message.messageDelete(token, messageId),
    {
      onSuccess: () => {
        refetchMessages();
        goBack();
        showFeedback({
          title: 'Zpráva byla smazána.',
          type: 'success',
        });
      },
      onError: err => {
        showFeedback({
          title: 'Zpráva nebyla smazána, zkuste to prosím později.',
          type: 'danger',
          err,
        });
      },
    },
  );
};
