"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebhookReporter = void 0;
const console_reporter_1 = require("./console-reporter");
function formatError(err) {
    if (!err)
        return "";
    if (err instanceof Error)
        return err.stack || err.message;
    return String(err);
}
class WebhookReporter extends console_reporter_1.ConsoleReporter {
    constructor(webhookUrl, runName) {
        super();
        this.webhookUrl = webhookUrl;
        this.runName = runName;
        this.startedAt = new Date();
        this.accumulated = [];
        this.currentSteps = [];
    }
    onStepEnd(args) {
        super.onStepEnd(args);
        this.currentSteps.push({
            phase: String(args.phase),
            operation: args.step.op,
            name: args.step.name,
            ok: args.ok,
            durationMs: args.durationMs,
            error: args.error ? formatError(args.error) : undefined,
        });
    }
    onScenarioEnd(scenario, result) {
        super.onScenarioEnd(scenario, result);
        this.accumulated.push({
            id: scenario.id,
            name: scenario.name,
            ok: result.ok,
            durationMs: result.durationMs,
            error: result.error ? formatError(result.error) : undefined,
            steps: [...this.currentSteps],
        });
        this.currentSteps = [];
    }
    async flush(exitCode) {
        const completedAt = new Date();
        const payload = {
            runName: this.runName,
            startedAt: this.startedAt.toISOString(),
            completedAt: completedAt.toISOString(),
            durationMs: completedAt.getTime() - this.startedAt.getTime(),
            exitCode,
            total: this.accumulated.length,
            passed: this.accumulated.filter((s) => s.ok).length,
            failed: this.accumulated.filter((s) => !s.ok).length,
            scenarios: this.accumulated,
        };
        try {
            const response = await fetch(this.webhookUrl, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(payload),
                signal: AbortSignal.timeout(10_000),
            });
            if (!response.ok) {
                console.warn(`[WebhookReporter] Webhook returned ${response.status}`);
            }
        }
        catch (err) {
            console.warn(`[WebhookReporter] Failed to deliver test results: ${err}`);
        }
    }
}
exports.WebhookReporter = WebhookReporter;
//# sourceMappingURL=webhook-reporter.js.map