import i18next from "i18next";
import { acquire as fetchTuitioData } from "@flare/tuitio-client";
import { NetworkError, ServerError } from "./errors";

const getHeaders = (): HeadersInit => {
  const { token } = fetchTuitioData();
  const language = i18next.language;

  const headers: HeadersInit = {
    "Content-Type": "application/json"
  };

  if (token) {
    headers.Authorization = `Tuitio ${token}`;
  }

  if (language) {
    headers["Accept-Language"] = language;
  }

  return headers;
};

const fetcher = async (url: string) => {
  const res = await fetch(url, { method: "GET", headers: getHeaders() });

  if (!res.ok) {
    const serverError = (await res.json()) as ServerError;
    const error = new NetworkError("An error occurred while fetching the data.", res.status, serverError);
    throw error;
  }

  return res.json();
};

async function mutationFetcher<Command>(url: string, { arg }: { arg: Command }) {
  const hasBody = arg !== undefined && arg !== null;
  const headers = getHeaders();
  const body = hasBody ? JSON.stringify(arg) : undefined;

  const res = await fetch(url, {
    method: "POST",
    headers,
    body
  });

  if (!res.ok) {
    const serverError = (await res.json()) as ServerError;
    const error = new NetworkError("An error occurred while mutating the data.", res.status, serverError);
    throw error;
  }

  return res.json();
}

export { fetcher, mutationFetcher };
