const backend = "http://localhost/api";

export function login(username, password) {
  return postJson("/auth/login", { username, password }).then(parseJSON);
}

export function register(username: string, password: string) {
  return postJson("/auth/register", { username, password }).then(parseJSON);
}

export function postAccount(refreshToken) {
  return postJson("/auth/account", { token: refreshToken }).then(parseJSON);
}

export function postToken(refreshToken) {
  return postJson("/auth/token", { token: refreshToken }).then(parseJSON);
}

export function getProducts(productName, token) {
  return getAuthenticatedJson(`/product?title=${productName}`, token).then(
    parseJSON
  );
}

export function getTracking(date, token) {
  return getAuthenticatedJson(`/tracking?date=${date}`, token).then(parseJSON);
}

export function postTracking(params, token) {
  return postAuthenticatedJson("/tracking", params, token).then(parseJSON);
}

export function deleteTracking(id, token) {
  return deleteAuthenticated("/tracking", id, token);
}

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  } else {
    throw new Error(response.statusText);
  }
}

function postJson(endpoint, params = {}) {
  return fetch(`${backend}${endpoint}`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify(params),
  }).then(checkStatus);
}

function getAuthenticatedJson(endpoint, token) {
  return fetch(`${backend}${endpoint}`, {
    method: "GET",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      Accept: "application/json",
    },
  }).then(checkStatus);
}

function postAuthenticatedJson(endpoint, params, token) {
  return fetch(`${backend}${endpoint}`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify(params),
  }).then(checkStatus);
}

function deleteAuthenticated(endpoint, params, token) {
  return fetch(`${backend}${endpoint}`, {
    method: "DELETE",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify(params),
  }).then(checkStatus);
}
