import { makeFetch } from "ChillMainAssets/lib/api/apiMethods";

/*
 * GET a person by id
 */
const getPerson = (id) => {
  const url = `/api/1.0/person/person/${id}.json`;
  return fetch(url).then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw Error("Error with request resource response");
  });
};

const getPersonAltNames = () =>
  fetch("/api/1.0/person/config/alt_names.json").then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw Error("Error with request resource response");
  });

const getCivilities = () =>
  fetch("/api/1.0/main/civility.json").then((response) => {
    if (response.ok) {
      return response.json();
    }
    throw Error("Error with request resource response");
  });

const getGenders = () => makeFetch("GET", "/api/1.0/main/gender.json");
// .then(response => {
//     console.log(response)
//     if (response.ok) { return response.json(); }
//     throw Error('Error with request resource response');
// });

const getCentersForPersonCreation = () =>
  makeFetch("GET", "/api/1.0/person/creation/authorized-centers", null);

/*
 * POST a new person
 */
const postPerson = (body) => {
  const url = `/api/1.0/person/person.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");
  });
};

/*
 * PATCH an existing person
 */
const patchPerson = (id, body) => {
  const url = `/api/1.0/person/person/${id}.json`;
  return fetch(url, {
    method: "PATCH",
    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 {
  getCentersForPersonCreation,
  getPerson,
  getPersonAltNames,
  getCivilities,
  getGenders,
  postPerson,
  patchPerson,
};
