import { HttpCodedError } from "../config";

export abstract class BaseAPI {
  protected async makePostRequest(
    url: string,
    requestData: object
  ): Promise<any> {
    try {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestData),
      });
      if (!response.ok) {
        const text = await response.text();
        var errorData = JSON.parse(text);
        throw new HttpCodedError(errorData.message, errorData.code.toString());
      }
      return await response.json();
    } catch (error) {
      throw error;
    }
  }

  protected async makePatchRequest(
    url: string,
    requestData: object
  ): Promise<any> {
    try {
      const response = await fetch(url, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestData),
      });
      if (!response.ok) {
        const text = await response.text();
        var errorData = JSON.parse(text);
        throw new HttpCodedError(errorData.message, response.status.toString());
      }
      return await response.json();
    } catch (error) {
      if (error instanceof HttpCodedError) {
        throw error;
      } else {
        throw new HttpCodedError("500", (error as Error).message || "Unexpected error");
      }
    }
  }
}
