import {
  BE_GESTIONEMAIL_SEARCH_RECIPIENTS_URL,
  BE_GESTIONEMAIL_SEND_EMAIL_URL,
} from '@/utils/Url';
import { errorHandler, requestResponseHandler } from './actionsHandlers';
import { getCsrfToken } from '@/utils/getCsrfToken';

// Recherche de destinataires pour email
export const searchRecipients = (establishmentId, query) => {
  const url = `${BE_GESTIONEMAIL_SEARCH_RECIPIENTS_URL}/?establishment_id=${establishmentId}&q=${encodeURIComponent(query)}`;
  return fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};
// Envoyer un email
export const sendEmail = async (messageData) => {
  const csrfToken = getCsrfToken();
  return fetch(BE_GESTIONEMAIL_SEND_EMAIL_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRFToken': csrfToken,
    },
    credentials: 'include',
    body: JSON.stringify(messageData),
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};
