import fetch from 'node-fetch';

const BASE_URL = 'http://users-dev.madbean.ovh';
const PATH = '/users';

const getJSONFromRelativeURL = relativeURL => fetch(`${BASE_URL}${relativeURL}`)
  .then(res => res.json());

const getUsers = () => getJSONFromRelativeURL(PATH)
  .then(json => json.data.users);

const getUserByURL = relativeURL => getJSONFromRelativeURL(relativeURL)
  .then(json => json.data.user)
  .catch(err => null);

const getUser = id => getUserByURL(`${PATH}/${id}`);

const addUser = (user) => {
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify(user),
  };

  fetch(`${BASE_URL}${PATH}`, options)
    .then(response => response.json())
    .then(json => json)
    .catch(console.log);
};

const updateUser = (user) => {
  const options = {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify(user),
  };

  fetch(`${BASE_URL}${PATH}/${user.userID}`, options)
    .then(response => response.json())
    .then(json => json)
    .catch(console.log);
};

export default {
  updateUser,
  addUser,
  getUser,
  getUsers,
  PATH,
  getUserByURL,
};
