"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpClient = void 0;
const AppError_js_1 = require("../../shared/errors/AppError.js");
class HttpClient {
    options;
    constructor(options) {
        this.options = options;
    }
    async get(path, headers) {
        return this.request("GET", path, undefined, headers);
    }
    async post(path, body, headers) {
        return this.request("POST", path, body, headers);
    }
    async put(path, body, headers) {
        return this.request("PUT", path, body, headers);
    }
    async delete(path, body, headers) {
        return this.request("DELETE", path, body, headers);
    }
    async request(method, path, body, headers) {
        const url = new URL(path, this.options.baseUrl).toString();
        let response;
        try {
            response = await fetch(url, {
                method,
                headers: {
                    "Content-Type": "application/json",
                    ...this.options.defaultHeaders,
                    ...headers
                },
                body: body === undefined ? undefined : JSON.stringify(body)
            });
        }
        catch (error) {
            throw new AppError_js_1.ExternalApiError(`Network request failed for ${method} ${path}`, "HTTP_NETWORK_ERROR", {
                url,
                cause: error instanceof Error ? { name: error.name, message: error.message } : error
            });
        }
        const text = await response.text();
        const parsed = text ? this.safeParse(text) : undefined;
        if (!response.ok) {
            throw new AppError_js_1.ExternalApiError(`HTTP ${response.status} from ${method} ${path}`, "HTTP_REQUEST_FAILED", {
                status: response.status,
                body: parsed ?? text
            });
        }
        return parsed;
    }
    safeParse(text) {
        try {
            return JSON.parse(text);
        }
        catch {
            return text;
        }
    }
}
exports.HttpClient = HttpClient;
