import {getCookieValue} from '@/router/guards';

class FetchError extends Error {
  response: Response;

  constructor(response: Response, message = 'HTTP error ' + response.status) {
    super(message);
    this.response = response;
  }
}

export const itFetch = (url: RequestInfo, options: RequestInit) => {
  return fetch(url, options).then(response => {
    if (!response.ok) {
      throw new FetchError(response);
    }

    return response;
  });
};

export const itPost = (
  url: RequestInfo,
  data: unknown,
  options: RequestInit = {},
) => {
  options = Object.assign({}, options);

  const headers = Object.assign({
    Accept: 'application/json',
    'Content-Type': 'application/json;charset=UTF-8',
  }, options?.headers);

  if (options?.headers) {
    delete options.headers;
  }

  options = Object.assign({
    method: 'POST',
    headers: headers,
    body: JSON.stringify(data)
  }, options);

  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  options.headers['X-CSRFToken'] = getCookieValue('csrftoken');

  if (options.method === 'GET') {
    delete options.body;
  }

  return itFetch(url, options).then((response) => {
    return response.json().catch(() => {
      return Promise.resolve(null);
    });
  });
};

export const itGet = (url: RequestInfo) => {
  return itPost(url, {}, {method: 'GET'});
};
