import axios from "axios";
import { Error } from "../types/error";

export default class WebRequest {
  /**
   * Gets a response from the given URL.
   *
   * @param url the url
   * @returns the response
   */
  public static get<T>(url: string): Promise<T> {
    return new Promise(async (resolve, reject) => {
      const response = await axios.get(url, {
        validateStatus: () => true, // Don't throw errors
        headers: {
          "User-Agent": "McUtils-JS-Library/1.0",
        },
      });

      const data = response.data;

      // Reject if the status code is not 200
      if (response.status !== 200) {
        reject(data as Error);
        return;
      }

      // Resolve with a buffer if the content type is an image
      if (response.headers["content-type"].includes("image/")) {
        resolve(Buffer.from(data, "utf-8") as unknown as T);
        return;
      }

      // Resolve with the data
      resolve(data as T);
    });
  }
}