"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiAdapter = void 0;
const axios_1 = __importDefault(require("axios"));
function hasHeader(headers, name) {
    return Object.prototype.hasOwnProperty.call(headers, name.toLowerCase());
}
class ApiAdapter {
    constructor(opts) {
        this.baseUrl = opts?.baseUrl;
        this.defaultHeaders = opts?.defaultHeaders;
    }
    async http(req) {
        const headers = {
            ...(this.defaultHeaders ?? {}),
            ...(req.headers ?? {}),
        };
        if (req.formData) {
            const formHeaders = req.formData.getHeaders();
            for (const [key, value] of Object.entries(formHeaders)) {
                headers[key.toLowerCase()] = String(value);
            }
        }
        else if (req.json !== undefined && !hasHeader(headers, "content-type")) {
            headers["content-type"] = "application/json";
        }
        const response = await axios_1.default.request({
            baseURL: this.baseUrl,
            url: req.url,
            method: req.method,
            headers,
            data: req.formData ?? (req.json !== undefined ? req.json : req.bodyText),
            responseType: "text",
            transformResponse: (data) => data,
            validateStatus: () => true,
        });
        const bodyText = typeof response.data === "string"
            ? response.data
            : String(response.data);
        const responseHeaders = Object.fromEntries(Object.entries(response.headers ?? {}).map(([key, value]) => [
            key.toLowerCase(),
            Array.isArray(value) ? value.join(", ") : String(value),
        ]));
        let bodyJson;
        const contentType = responseHeaders["content-type"] ?? "";
        if (contentType.toLowerCase().includes("application/json")) {
            try {
                bodyJson = JSON.parse(bodyText);
            }
            catch {
            }
        }
        if (bodyJson === undefined) {
            const trimmed = bodyText.trim();
            if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
                try {
                    bodyJson = JSON.parse(trimmed);
                }
                catch {
                }
            }
        }
        const apiResponse = {
            status: response.status,
            headers: responseHeaders,
            bodyText,
            ...(bodyJson !== undefined ? { bodyJson } : {}),
        };
        return apiResponse;
    }
}
exports.ApiAdapter = ApiAdapter;
//# sourceMappingURL=api-adapter.js.map