/**
 *  It takes a URL, a method, and a body, and returns a promise that resolves to a JSON object
 */
export class ApiUtil {
  /**
   * It returns a promise that resolves to a JSON object of type T
   *
   * @typedef T generic type
   * @param {string} url - The url to make the request to.
   * @param {HeadersInit} headers - HeadersInit
   * @returns {Promise<T>}A promise of type T
   */
  static async get(url, headers) {
    return await ApiUtil.getResponseInJSON(url, 'GET', headers, undefined);
  }
  /**
   * It takes a URL, a method, some headers, and some data, and returns a promise that resolves to the
   * response in JSON format
   *
   * @typedef T generic type
   * @param {string} url - The URL to make the request to.
   * @param {unknown} data - The data to send to the server.
   * @param {HeadersInit} headers - HeadersInit
   * @returns {Promise<T>} A promise that resolves to the response in JSON format.
   */
  static async post(url, data, headers) {
    return await ApiUtil.getResponseInJSON(url, 'POST', headers, JSON.stringify(data));
  }
  /**
   * It takes a URL, a method, a set of headers, and an optional body, and returns a promise that
   * resolves to a JSON object
   *
   * @typedef T generic type
   * @param {string} url - The URL to send the request to.
   * @param {string} method - The HTTP method to use.
   * @param {HeadersInit} headers - HeadersInit - This is the headers that will be sent with the
   * request.
   * @param {string} [body] - The body of the request.
   * @returns {Promise<T>} A promise that resolves to a JSON object.
   */
  static async getResponseInJSON(url, method, headers, body) {
    if (headers) {
      headers['Content-Type'] = 'application/json';
    }
    else {
      headers = {
        // eslint-disable-next-line @typescript-eslint/naming-convention
        'Content-Type': 'application/json',
      };
    }
    try {
      const response = await fetch(url, {
        method,
        body,
        headers,
      });
      return response.json();
    }
    catch (e) {
      throw new Error(JSON.stringify({}));
    }
  }
}
