import axios from "axios";
import i18next from "i18next";
import { fetch as fetchTuitioData } from "@flare/tuitio-client";

function getHeaders() {
  const { token } = fetchTuitioData();
  const language = i18next.language;

  return {
    "Content-Type": "application/json",
    Authorization: `Tuitio ${token}`,
    "Accept-Language": `${language}`
  };
}

async function internalRequest(url, options) {
  try {
    const res = await axios.request(url, options);
    return res.data;
  } catch (error) {
    if (error.response && error.response.data) {
      throw (
        {
          ...error.response.data,
          message: error.response.data.detail || error.response.data.title
        } || error
      );
    }
    // The request was made but no response was received
    // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
    // http.ClientRequest in node.js
    throw error;
  }
}

export const request = (url, options) => internalRequest(url, options);

export function post(url, data) {
  const options = {
    method: "post",
    data: JSON.stringify(data),
    headers: getHeaders()
  };

  return internalRequest(url, options);
}

export function put(url, data) {
  const options = {
    method: "put",
    data: JSON.stringify(data),
    headers: getHeaders()
  };

  return internalRequest(url, options);
}

export function del(url, data) {
  const options = {
    method: "delete",
    data: JSON.stringify(data),
    headers: getHeaders()
  };

  return internalRequest(url, options);
}

export function get(url) {
  const options = {
    method: "GET",
    headers: getHeaders()
  };
  return internalRequest(url, options);
}
