"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getVariableKeyByProcessInstanceKey = void 0;
const test_1 = require("@playwright/test");
const apiHelpers_1 = require("./apiHelpers");
const sleep_1 = require("./sleep");
async function getVariableKeyByProcessInstanceKey(processInstanceKey, variableName, authToken, environment, clusterType, maxRetries = 10, retryDelayMs = 2000) {
    const apiRequestContext = await (0, apiHelpers_1.getApiRequestContext)();
    const url = (0, apiHelpers_1.buildZeebeApiUrl)('/v2/variables/search', environment, clusterType);
    let lastError = null;
    // Retry logic to wait for variable 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),
                        name: variableName,
                    },
                },
            });
            (0, test_1.expect)(response.status()).toBe(200);
            const responseBody = await response.json();
            if (responseBody?.items && responseBody.items.length > 0) {
                const variableKey = responseBody.items[0]?.variableKey;
                if (variableKey != null) {
                    console.log(`Found variable key ${variableKey} for ${variableName} on attempt ${attempt}`);
                    return String(variableKey);
                }
            }
            lastError = new Error(`No variable ${variableName} found for processInstanceKey: ${processInstanceKey}`);
        }
        catch (error) {
            lastError = error;
        }
        if (attempt < maxRetries) {
            console.log(`Variable ${variableName} not found yet, retrying in ${retryDelayMs}ms (${attempt}/${maxRetries})...`);
            await (0, sleep_1.sleep)(retryDelayMs);
        }
    }
    throw new Error(`Failed to find variable ${variableName} after ${maxRetries} attempts: ${lastError?.message}`);
}
exports.getVariableKeyByProcessInstanceKey = getVariableKeyByProcessInstanceKey;
