"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpHybxClient = void 0;
const config_1 = require("./config");
/**
 * HTTP HYBX client — uses api-fineract-unified spec (Volume 20).
 * Production allowed when HYBX_UNIFIED_API_OK=1 and unified manifest exists.
 */
class HttpHybxClient {
    environment;
    config;
    constructor(options) {
        this.config = options?.config ?? (0, config_1.loadHybxConfig)({ testMode: options?.testMode ?? true });
        this.environment = this.config.environment;
        const unifiedOk = process.env.HYBX_UNIFIED_API_OK === '1' || options?.allowProduction === true;
        if (this.config.environment === 'production' && !unifiedOk) {
            throw new Error('HttpHybxClient production requires HYBX_UNIFIED_API_OK=1 (api-fineract-unified.v1.openapi.yaml integrated)');
        }
    }
    async postJson(path, body) {
        const controller = new AbortController();
        const timeout = setTimeout(() => controller.abort(), this.config.requestTimeoutMs);
        try {
            const res = await fetch(`${this.config.baseUrl}${path}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-API-Key': this.config.apiKey,
                    Authorization: `Bearer ${this.config.clientSecret}`,
                },
                body: JSON.stringify(body),
                signal: controller.signal,
            });
            if (!res.ok) {
                throw new Error(`HYBX HTTP ${res.status}: ${await res.text()}`);
            }
            return (await res.json());
        }
        finally {
            clearTimeout(timeout);
        }
    }
    async initiatePayment(request) {
        return this.postJson('/v1/payments', request);
    }
    async getPaymentStatus(paymentId) {
        const res = await fetch(`${this.config.baseUrl}/v1/payments/${paymentId}`, {
            headers: { 'X-API-Key': this.config.apiKey },
        });
        if (!res.ok)
            throw new Error(`HYBX HTTP ${res.status}`);
        return (await res.json());
    }
    async listSettlementEvents(since) {
        const q = since ? `?since=${encodeURIComponent(since)}` : '';
        const res = await fetch(`${this.config.baseUrl}/v1/settlement-events${q}`, {
            headers: { 'X-API-Key': this.config.apiKey },
        });
        if (!res.ok)
            throw new Error(`HYBX HTTP ${res.status}`);
        return (await res.json());
    }
    parseWebhookPayload(body) {
        const parsed = JSON.parse(body);
        return {
            eventType: String(parsed.eventType ?? 'unknown'),
            eventId: String(parsed.eventId ?? ''),
            timestamp: String(parsed.timestamp ?? new Date().toISOString()),
            data: parsed.data ?? parsed,
        };
    }
}
exports.HttpHybxClient = HttpHybxClient;
