"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getIncidentKeyByProcessInstanceKey = void 0;
const test_1 = require("@playwright/test");
const apiHelpers_1 = require("./apiHelpers");
const sleep_1 = require("./sleep");
async function getIncidentKeyByProcessInstanceKey(processInstanceKey, authToken, environment, clusterType, maxRetries = 10, retryDelayMs = 2000) {
    const apiRequestContext = await (0, apiHelpers_1.getApiRequestContext)();
    const url = (0, apiHelpers_1.buildZeebeApiUrl)('/v2/incidents/search', environment, clusterType);
    let lastError = null;
    // Retry logic to wait for incident to be created and indexed
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
        try {
            const response = await apiRequestContext.post(url, {
                headers: { Authorization: authToken ?? '' },
                data: { filter: { processInstanceKey: String(processInstanceKey) } },
            });
            (0, test_1.expect)(response.status()).toBe(200);
            const responseBody = await response.json();
            if (responseBody?.items && responseBody.items.length > 0) {
                const incidentKey = responseBody.items[0]?.incidentKey;
                if (incidentKey != null) {
                    console.log(`Found incident key ${incidentKey} on attempt ${attempt}`);
                    return String(incidentKey);
                }
            }
            lastError = new Error(`No incidents found for processInstanceKey: ${processInstanceKey}`);
        }
        catch (error) {
            lastError = error;
        }
        if (attempt < maxRetries) {
            console.log(`Incident not found yet, retrying in ${retryDelayMs}ms (${attempt}/${maxRetries})...`);
            await (0, sleep_1.sleep)(retryDelayMs);
        }
    }
    throw new Error(`Failed to find incident after ${maxRetries} attempts: ${lastError?.message}`);
}
exports.getIncidentKeyByProcessInstanceKey = getIncidentKeyByProcessInstanceKey;
