import { getSocialIssues } from "ChillPersonAssets/vuejs/AccompanyingCourse/api.js";
import { fetchResults } from "ChillMainAssets/lib/api/apiMethods";

/*
 *  Load socialActions by socialIssue (id)
 */
const getSocialActionByIssue = (id) => {
  const url = `/api/1.0/person/social/social-action/by-social-issue/${id}.json`;
  return fetch(url).then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw Error("Error with request resource response");
  });
};

const getLocations = () => fetchResults("/api/1.0/main/location.json");

const getLocationTypes = () => fetchResults("/api/1.0/main/location-type.json");

const getUserCurrentLocation = () =>
  fetch("/api/1.0/main/user-current-location.json").then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw Error("Error with request resource response");
  });

/*
 *   Load Location Type by defaultFor
 *   @param {string} entity - can be "person" or "thirdparty"
 */
const getLocationTypeByDefaultFor = (entity) => {
  return getLocationTypes().then(
    (results) => results.filter((t) => t.defaultFor === entity)[0],
  );
};

/**
 * Post a location
 *
 * **NOTE**: also in use for Calendar
 * @param body
 * @returns {Promise<T>}
 */
const postLocation = (body) => {
  const url = `/api/1.0/main/location.json`;
  return fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json;charset=utf-8",
    },
    body: JSON.stringify(body),
  }).then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw Error("Error with request resource response");
  });
};

export {
  getSocialIssues,
  getSocialActionByIssue,
  getLocations,
  getLocationTypes,
  getLocationTypeByDefaultFor,
  postLocation,
  getUserCurrentLocation,
};
