import axios from 'axios';

import { userMapper } from '../Mapper';

const url = 'https://users-dev.madbean.ovh/';

const instance = axios.create({
  baseURL: url,
  timeout: 10000,
});

const saveUser = user => instance.post('/users', user);

const updateUser = (id, user) => instance.put(`/users/${id}`, user);

const getUser = id => instance.get(`/users/${id}`).then(data => data);

const updateOrSaveUser = async (user) => {
  const mappedUser = userMapper(user);
  const jsonUser = JSON.stringify(mappedUser);
  try {
    const result = await getUser(mappedUser.userID);
    if (!result.data.data.user) {
      saveUser(jsonUser);
    } else {
      updateUser(mappedUser.userID, jsonUser);
    }
  } catch (err) {
    console.log(err);
  }
};

export default {
  saveUser,
  updateUser,
  getUser,
  updateOrSaveUser,
};
