import {
  BE_GESTIONMESSAGERIE_CONVERSATIONS_URL,
  BE_GESTIONMESSAGERIE_CONVERSATION_MESSAGES_URL,
  BE_GESTIONMESSAGERIE_MARK_AS_READ_URL,
  BE_GESTIONMESSAGERIE_MESSAGES_URL,
  BE_GESTIONMESSAGERIE_SEARCH_RECIPIENTS_URL,
} from '@/utils/Url';
import { errorHandler, requestResponseHandler } from './actionsHandlers';

export const fetchConversations = (profileId) => {
  return fetch(`${BE_GESTIONMESSAGERIE_CONVERSATIONS_URL}/${profileId}/`, {
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const fetchMessages = (conversationId) => {
  return fetch(
    `${BE_GESTIONMESSAGERIE_CONVERSATION_MESSAGES_URL}/${conversationId}/`,
    {
      headers: {
        'Content-Type': 'application/json',
      },
    }
  )
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const sendMessage = (data) => {
  return fetch(`${BE_GESTIONMESSAGERIE_MESSAGES_URL}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const markAsRead = (conversationId, profileId) => {
  return fetch(`${BE_GESTIONMESSAGERIE_MARK_AS_READ_URL}/${conversationId}/`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ profile_id: profileId }),
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};

export const searchRecipients = (establishmentId, query) => {
  const url = `${BE_GESTIONMESSAGERIE_SEARCH_RECIPIENTS_URL}/?establishment_id=${establishmentId}&q=${encodeURIComponent(query)}`;
  return fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(requestResponseHandler)
    .catch(errorHandler);
};
