"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUserTaskKeyByProcessInstanceKey = void 0;
const test_1 = require("@playwright/test");
const apiHelpers_1 = require("./apiHelpers");
const sleep_1 = require("./sleep");
async function getUserTaskKeyByProcessInstanceKey(processInstanceKey, authToken, environment, clusterType, maxRetries = 10, retryDelayMs = 2000) {
    const apiRequestContext = await (0, apiHelpers_1.getApiRequestContext)();
    const url = (0, apiHelpers_1.buildZeebeApiUrl)('/v2/user-tasks/search', environment, clusterType);
    let lastError = null;
    // Retry logic to wait for user task to be 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 userTaskKey = responseBody.items[0]?.userTaskKey;
                if (userTaskKey != null) {
                    console.log(`Found user task key ${userTaskKey} for process instance ${processInstanceKey} on attempt ${attempt}`);
                    return String(userTaskKey);
                }
            }
            lastError = new Error(`No user tasks found for processInstanceKey: ${processInstanceKey}`);
        }
        catch (error) {
            lastError = error;
        }
        // Wait before retrying (except on last attempt)
        if (attempt < maxRetries) {
            console.log(`User task not found yet for process instance ${processInstanceKey}, retrying in ${retryDelayMs}ms (attempt ${attempt}/${maxRetries})...`);
            await (0, sleep_1.sleep)(retryDelayMs);
        }
    }
    throw new Error(`Failed to find user task after ${maxRetries} attempts: ${lastError?.message}`);
}
exports.getUserTaskKeyByProcessInstanceKey = getUserTaskKeyByProcessInstanceKey;
