"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiHandler = void 0;
const axios_1 = __importDefault(require("axios"));
class ApiHandler {
    constructor(baseUrl, defaultHeaders = {}, timeout = 3000, retries = 2) {
        this.baseUrl = baseUrl;
        this.defaultHeaders = defaultHeaders;
        this.timeout = timeout;
        this.retries = retries;
        this.axiosInstance = axios_1.default.create({
            baseURL: this.baseUrl,
            headers: this.defaultHeaders,
            timeout: this.timeout,
        });
    }
    async get(endpoint, headers, params) {
        console.log(endpoint);
        console.log(this.buildUrl(endpoint));
        return this.handleRequest({
            method: "GET",
            url: this.buildUrl(endpoint),
            headers: Object.assign(Object.assign({}, this.defaultHeaders), headers),
            params,
        });
    }
    async post(endpoint, data, headers, jsonData) {
        return this.handleRequest({
            method: "POST",
            url: this.buildUrl(endpoint),
            headers: Object.assign(Object.assign({}, this.defaultHeaders), headers),
            data: jsonData || data,
        });
    }
    async put(endpoint, data, headers, jsonData) {
        return this.handleRequest({
            method: "PUT",
            url: this.buildUrl(endpoint),
            headers: Object.assign(Object.assign({}, this.defaultHeaders), headers),
            data: jsonData || data,
        });
    }
    async delete(endpoint, headers) {
        return this.handleRequest({
            method: "DELETE",
            url: this.buildUrl(endpoint),
            headers: Object.assign(Object.assign({}, this.defaultHeaders), headers),
        });
    }
    async patch(endpoint, headers, data, jsonData) {
        return this.handleRequest({
            method: "PATCH",
            url: this.buildUrl(endpoint),
            headers: Object.assign(Object.assign({}, this.defaultHeaders), headers),
            data: jsonData || data,
        });
    }
    buildUrl(endpoint) {
        return this.baseUrl ? `${this.baseUrl.replace(/\/$/, "")}/${endpoint.replace(/^\//, "")}` : endpoint;
    }
    async handleRequest(config) {
        for (let attempt = 0; attempt < this.retries; attempt++) {
            try {
                const response = await this.axiosInstance.request(config);
                return response.data;
            }
            catch (error) {
                console.error(`Attempt ${attempt + 1} failed:`, error);
                if (attempt + 1 === this.retries) {
                    throw error;
                }
            }
        }
        return null;
    }
}
exports.ApiHandler = ApiHandler;
