import { createHmac, randomUUID } from "node:crypto";
export class CallbackClient {
    secret;
    constructor(secret) {
        this.secret = secret;
    }
    async deliver(callbackUrl, event) {
        const payload = JSON.stringify({ ...event, eventId: event.eventId ?? randomUUID() });
        let lastError;
        for (let attempt = 0; attempt < 4; attempt += 1) {
            const timestamp = String(Date.now());
            const signature = createHmac("sha256", this.secret).update(`${timestamp}.${payload}`).digest("hex");
            try {
                const response = await fetch(callbackUrl, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-BGM-Bridge-Timestamp": timestamp,
                        "X-BGM-Bridge-Signature": `sha256=${signature}`,
                    },
                    body: payload,
                    signal: AbortSignal.timeout(15_000),
                });
                if (response.ok)
                    return;
                lastError = new Error(`ERP callback returned ${response.status}`);
            }
            catch (error) {
                lastError = error instanceof Error ? error : new Error("ERP callback failed");
            }
            await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt));
        }
        throw lastError ?? new Error("ERP callback failed");
    }
}
