import { BE_PLANNING_PLANNINGS_URL, BE_PLANNING_EVENTS_URL } from '@/utils/Url';
import { fetchWithAuth } from '@/utils/fetchWithAuth';

const getData = (url) => {
  return fetchWithAuth(url);
};

const createDatas = (url, newData, csrfToken) => {
  return fetchWithAuth(url, {
    method: 'POST',
    headers: { 'X-CSRFToken': csrfToken },
    body: JSON.stringify(newData),
  });
};

const updateDatas = (url, updatedData, csrfToken) => {
  return fetchWithAuth(url, {
    method: 'PUT',
    headers: { 'X-CSRFToken': csrfToken },
    body: JSON.stringify(updatedData),
  });
};

const removeDatas = (url, csrfToken) => {
  return fetchWithAuth(url, {
    method: 'DELETE',
    headers: { 'X-CSRFToken': csrfToken },
  });
};

export const fetchPlannings = (
  establishment_id = null,
  planningMode = null
) => {
  let url = `${BE_PLANNING_PLANNINGS_URL}`;
  if (establishment_id) {
    url += `?establishment_id=${establishment_id}`;
  }
  if (planningMode) {
    url += `&planning_mode=${planningMode}`;
  }
  return getData(url);
};

export const getPlanning = (id) => {
  return getData(`${BE_PLANNING_PLANNINGS_URL}/${id}`);
};

export const createPlanning = (newData, csrfToken) => {
  return createDatas(`${BE_PLANNING_PLANNINGS_URL}`, newData, csrfToken);
};

export const updatePlanning = (id, newData, csrfToken) => {
  return updateDatas(`${BE_PLANNING_PLANNINGS_URL}/${id}`, newData, csrfToken);
};

export const deletePlanning = (id, csrfToken) => {
  return removeDatas(`${BE_PLANNING_PLANNINGS_URL}/${id}`, csrfToken);
};

export const fetchEvents = (establishment_id = null, planningMode = null) => {
  let url = `${BE_PLANNING_EVENTS_URL}`;
  if (establishment_id) {
    url += `?establishment_id=${establishment_id}`;
  }
  if (planningMode) {
    url += `&planning_mode=${planningMode}`;
  }

  return getData(url);
};

export const getEvent = (id) => {
  return getData(`${BE_PLANNING_EVENTS_URL}/${id}`);
};

export const createEvent = (newData, csrfToken) => {
  return createDatas(`${BE_PLANNING_EVENTS_URL}`, newData, csrfToken);
};

export const updateEvent = (id, newData, csrfToken) => {
  return updateDatas(`${BE_PLANNING_EVENTS_URL}/${id}`, newData, csrfToken);
};

export const deleteEvent = (id, csrfToken) => {
  return removeDatas(`${BE_PLANNING_EVENTS_URL}/${id}`, csrfToken);
};

export const fetchUpcomingEvents = (establishment_id = null) => {
  let url = `${BE_PLANNING_EVENTS_URL}/upcoming`;
  if (establishment_id) {
    url += `?establishment_id=${establishment_id}`;
  }
  return getData(`${url}`);
};
