"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateCollectionScope = exports.createSingleProcessReport = exports.createDashboard = exports.createCollection = exports.getOptimizeCookieSm = exports.getOptimizeCoockie = exports.createStringClusterVariable = exports.createJsonClusterVariable = exports.createProcessInstance = exports.deployProcess = exports.validateMcpServerHealth = exports.authC8runAPI = exports.authSmAPI = exports.authSaasAPI = exports.authAPI = exports.buildZeebeApiUrl = exports.retryOn500 = exports.sendRequestAndAssertResponse = exports.assertResponseStatus = exports.getApiRequestContext = void 0;
const test_1 = require("@playwright/test");
const sleep_1 = require("./sleep");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const os_1 = __importDefault(require("os"));
const utils_1 = require("./utils");
let apiRequestContext;
// ---- Internal: API request context ----
async function getApiRequestContext() {
    if (!apiRequestContext) {
        apiRequestContext = await test_1.request.newContext();
    }
    return apiRequestContext;
}
exports.getApiRequestContext = getApiRequestContext;
// ---- Common HTTP helpers ----
async function assertResponseStatus(response, status) {
    (0, test_1.expect)(response.status()).toBe(status);
}
exports.assertResponseStatus = assertResponseStatus;
async function sendRequestAndAssertResponse(request, url, requestBody, maxRetries = 3) {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
        try {
            const options = requestBody && Object.keys(requestBody).length > 0
                ? { data: requestBody }
                : {};
            const response = await request.post(url, options);
            (0, test_1.expect)(response.status()).toBe(200);
            return;
        }
        catch (error) {
            if (attempt < maxRetries - 1) {
                console.warn(`Attempt ${attempt + 1} failed for getting response from ${url}. Retrying...`);
                await (0, sleep_1.sleep)(5000);
            }
            else {
                console.error(error);
                throw new Error(`URL response failed after ${maxRetries} attempts`);
            }
        }
    }
}
exports.sendRequestAndAssertResponse = sendRequestAndAssertResponse;
async function retryOn500(fn, maxAttempts = 3, delayMs = 3000) {
    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
        const res = await fn();
        if (res.status() !== 500 || attempt === maxAttempts)
            return res;
        await (0, sleep_1.sleep)(delayMs);
    }
    throw new Error('unreachable');
}
exports.retryOn500 = retryOn500;
// ---- Cluster Credentials Helper ----
function getClusterCredentials(clusterType) {
    if (!clusterType) {
        return {
            clientId: process.env.ZEEBE_API_CLIENT_ID,
            clientSecret: process.env.ZEEBE_API_CLIENT_SECRET,
            authUrl: process.env.ZEEBE_API_AUTH_URL,
            apiUrl: process.env.ZEEBE_API_URL,
            tokenAudience: process.env.ZEEBE_API_TOKEN_AUDIENCE,
        };
    }
    const suffix = clusterType.toUpperCase().replace(/[\s-]/g, '_');
    const clientId = process.env[`ZEEBE_API_CLIENT_ID_${suffix}`];
    const clientSecret = process.env[`ZEEBE_API_CLIENT_SECRET_${suffix}`];
    const authUrl = process.env[`ZEEBE_API_AUTH_URL_${suffix}`];
    const apiUrl = process.env[`ZEEBE_API_URL_${suffix}`];
    const tokenAudience = process.env[`ZEEBE_API_TOKEN_AUDIENCE_${suffix}`];
    if (!clientId || !clientSecret || !authUrl || !apiUrl || !tokenAudience) {
        throw new Error(`Credentials for cluster type "${clusterType}" not found. ` +
            `Expected env vars: ZEEBE_API_CLIENT_ID_${suffix}, etc.`);
    }
    return { clientId, clientSecret, authUrl, apiUrl, tokenAudience };
}
// ---- Zeebe: URL building (SaaS vs SM) ----
function inferZeebeEnvironment(override) {
    if (override) {
        return override;
    }
    if (process.env.MINOR_VERSION?.includes('SM')) {
        return 'sm';
    }
    if (process.env.ZEEBE_API_URL) {
        return 'saas';
    }
    return 'sm';
}
function normalizeOrigin(value, defaultProtocol = 'https') {
    const trimmed = value.trim().replace(/\/+$/, '');
    if (/^https?:\/\//i.test(trimmed)) {
        return trimmed;
    }
    return `${defaultProtocol}://${trimmed}`;
}
function getZeebeApiOrigin(environment, clusterType) {
    if (environment === 'saas') {
        // Use cluster-specific credentials if clusterType provided
        if (clusterType) {
            const creds = getClusterCredentials(clusterType);
            return creds.apiUrl.replace(/\/+$/, '');
        }
        const saasUrl = process.env.ZEEBE_API_URL?.trim();
        if (!saasUrl) {
            throw new Error('Missing ZEEBE_API_URL (SaaS).');
        }
        return saasUrl.replace(/\/+$/, '');
    }
    const baseUrl = process.env.BASE_URL?.trim();
    if (baseUrl) {
        return normalizeOrigin(baseUrl, 'https');
    }
    throw new Error('Missing BASE_URL (SM).');
}
function buildZeebeApiUrl(resourcePath, environmentOverride, clusterType) {
    const environment = inferZeebeEnvironment(environmentOverride);
    const baseUrl = getZeebeApiOrigin(environment, clusterType);
    const normalizedPath = resourcePath.startsWith('/')
        ? resourcePath
        : `/${resourcePath}`;
    const contextPath = process.env.ORCHESTRATION_CONTEXT_PATH ?? '/orchestration';
    const pathWithPrefix = environment === 'sm' ? `${contextPath}${normalizedPath}` : normalizedPath;
    return `${baseUrl}${pathWithPrefix}`;
}
exports.buildZeebeApiUrl = buildZeebeApiUrl;
async function authAPI(environment, audience = process.env.ZEEBE_API_TOKEN_AUDIENCE) {
    apiRequestContext = await getApiRequestContext();
    if (environment === 'saas') {
        const tokenResponse = await apiRequestContext.post('https://login.cloud.ultrawombat.com/oauth/token', {
            headers: {
                'Content-Type': 'application/json',
            },
            data: {
                audience,
                client_id: process.env.ZEEBE_API_CLIENT_ID,
                client_secret: process.env.ZEEBE_API_CLIENT_SECRET,
                grant_type: 'client_credentials',
            },
        });
        if (tokenResponse.status() !== 200) {
            const errorBody = await tokenResponse.text();
            throw new Error(`Failed to fetch access token. Response: ${errorBody}`);
        }
        const tokenJson = await tokenResponse.json();
        const bearerToken = `Bearer ${tokenJson.access_token}`;
        return bearerToken;
    }
    const baseUrlRaw = process.env.BASE_URL?.trim();
    if (!baseUrlRaw) {
        throw new Error('Missing BASE_URL (required for SM auth).');
    }
    const origin = normalizeOrigin(baseUrlRaw, 'https');
    const tokenUrl = `${origin}/auth/realms/camunda-platform/protocol/openid-connect/token`;
    const tokenResponse = await apiRequestContext.post(tokenUrl, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        form: {
            client_id: process.env.DISTRO_QA_E2E_TESTS_KEYCLOAK_CLIENT_ID ?? 'venom',
            client_secret: process.env.DISTRO_QA_E2E_TESTS_KEYCLOAK_ADMIN_SECRET,
            grant_type: 'client_credentials',
        },
    });
    if (tokenResponse.status() !== 200) {
        const errorBody = await tokenResponse.text();
        throw new Error(`Failed to fetch SM access token. Response: ${errorBody}`);
    }
    const tokenJson = await tokenResponse.json();
    const bearerToken = `Bearer ${tokenJson.access_token}`;
    return bearerToken;
}
exports.authAPI = authAPI;
async function authSaasAPI(audience, clusterType) {
    const creds = getClusterCredentials(clusterType);
    const tokenAudience = audience ?? creds.tokenAudience;
    apiRequestContext = await getApiRequestContext();
    const tokenResponse = await apiRequestContext.post(creds.authUrl, {
        headers: {
            'Content-Type': 'application/json',
        },
        data: {
            audience: tokenAudience,
            client_id: creds.clientId,
            client_secret: creds.clientSecret,
            grant_type: 'client_credentials',
        },
    });
    if (tokenResponse.status() !== 200) {
        const errorBody = await tokenResponse.text();
        throw new Error(`Failed to fetch access token. Response: ${errorBody}`);
    }
    const tokenJson = await tokenResponse.json();
    const bearerToken = `Bearer ${tokenJson.access_token}`;
    return bearerToken;
}
exports.authSaasAPI = authSaasAPI;
async function authSmAPI() {
    return authAPI('sm');
}
exports.authSmAPI = authSmAPI;
async function authC8runAPI(name, password) {
    apiRequestContext = await getApiRequestContext();
    const minorVersion = process.env.MINOR_VERSION;
    const prefix = minorVersion === 'c8Run-8.8' ? '' : '/api';
    await apiRequestContext.post(`${prefix}/login?username=${name}&password=${password}`, {
        headers: {
            'Content-Type': 'application/json',
        },
    });
    await apiRequestContext.storageState({ path: 'utils/.auth' });
}
exports.authC8runAPI = authC8runAPI;
// ---- MCP Server Health Check ----
async function validateMcpServerHealth(serverUrl) {
    apiRequestContext = await getApiRequestContext();
    const mcpServerUrl = serverUrl || process.env.MCP_SERVER_URL || 'http://localhost:12001';
    const healthEndpoint = `${mcpServerUrl}/actuator/health`;
    try {
        const response = await apiRequestContext.get(healthEndpoint);
        if (response.status() !== 200) {
            const errorBody = await response.text();
            throw new Error(`MCP server health check failed with status ${response.status()}. Response: ${errorBody}`);
        }
        return response;
    }
    catch (error) {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        throw new Error(`MCP server is not available at ${healthEndpoint}. ` +
            `Error: ${errorMessage}. ` +
            'Please ensure the MCP docker container is running with: ' +
            'docker run -d --name mcp-test-server --network host registry.camunda.cloud/mcp/mcp-test-server:latest');
    }
}
exports.validateMcpServerHealth = validateMcpServerHealth;
// ---- Zeebe: API helpers ----
async function deployProcess(filePath, authToken, environment, clusterType) {
    try {
        apiRequestContext = await getApiRequestContext();
        const fileContent = fs_1.default.readFileSync(filePath);
        const fileName = path_1.default.basename(filePath);
        const ext = path_1.default.extname(fileName).toLowerCase();
        const mimeType = ext === '.form'
            ? 'application/json'
            : ext === '.dmn'
                ? 'application/vnd.dmn+xml'
                : 'application/vnd.bpmn+xml';
        const resources = {
            name: fileName,
            mimeType,
            buffer: fileContent,
        };
        const url = buildZeebeApiUrl('/v2/deployments', environment, clusterType);
        const isMT = process.env.IS_MT === 'true';
        const multipart = { resources };
        if (isMT) {
            multipart.tenantId = '<default>';
        }
        const response = await apiRequestContext.post(url, {
            headers: {
                Authorization: authToken ?? '',
            },
            multipart,
        });
        if (response.status() !== 200) {
            const body = await response.text();
            console.error(`deployProcess failed for ${fileName}: HTTP ${response.status()} - ${body}`);
        }
        (0, test_1.expect)(response.status()).toBe(200);
        const responseJson = await response.json();
        if (!responseJson.deployments?.[0]?.processDefinition?.processDefinitionKey) {
            console.warn(`No processDefinitionKey found for ${fileName}; is fine if it's a form`);
            return null;
        }
        await (0, sleep_1.sleep)(10000);
        return responseJson.deployments[0].processDefinition.processDefinitionKey;
    }
    catch (err) {
        console.error(`Error during deployProcess for ${filePath}:`, err);
        return null;
    }
}
exports.deployProcess = deployProcess;
async function createProcessInstance(processDefinitionKey, authToken, environment, clusterType, variables) {
    apiRequestContext = await getApiRequestContext();
    const url = buildZeebeApiUrl('/v2/process-instances', environment, clusterType);
    const isMT = process.env.IS_MT === 'true';
    const data = {
        processDefinitionKey: String(processDefinitionKey),
        variables: variables ?? {},
    };
    if (isMT) {
        data.tenantId = '<default>';
    }
    // Retry on 400 (process definition not yet visible in Zeebe after deploy)
    const maxAttempts = 5;
    const retryDelayMs = 5000;
    let response;
    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
        response = await apiRequestContext.post(url, {
            headers: {
                Authorization: authToken ?? '',
            },
            data,
        });
        if (response.status() === 200)
            break;
        if (response.status() === 400 && attempt < maxAttempts) {
            console.warn(`createProcessInstance: got 400 for key ${processDefinitionKey}, attempt ${attempt}/${maxAttempts}, retrying in ${retryDelayMs}ms`);
            await (0, sleep_1.sleep)(retryDelayMs);
            continue;
        }
        break;
    }
    (0, test_1.expect)(response.status()).toBe(200);
    const responseBody = await response.json();
    const processInstanceKey = responseBody?.processInstanceKey;
    if (processInstanceKey == null) {
        throw new Error(`Expected processInstanceKey in createProcessInstance response, but got: ${JSON.stringify(responseBody, null, 2)}`);
    }
    return String(processInstanceKey);
}
exports.createProcessInstance = createProcessInstance;
async function createClusterVariableInternal(authToken, environment, variableName, variableValue, variableType, clusterType) {
    // Retry on transient ingress / upstream errors (502/503/504) and on
    // network-layer exceptions, which we have observed during nightly runs
    // when the orchestration cluster gateway is in the middle of a rollout.
    // The actual "create" semantics are idempotent because HTTP 409 is
    // already treated as success below.
    const maxAttempts = 5;
    const baseDelayMs = 2000;
    let lastErrorMessage = '';
    try {
        apiRequestContext = await getApiRequestContext();
        const url = buildZeebeApiUrl('/v2/cluster-variables/global', environment, clusterType);
        for (let attempt = 1; attempt <= maxAttempts; attempt++) {
            let status;
            let bodyText = '';
            try {
                const response = await apiRequestContext.post(url, {
                    headers: {
                        Authorization: authToken,
                    },
                    data: {
                        name: variableName,
                        value: variableValue,
                    },
                });
                status = response.status();
                if (status === 200 || status === 201 || status === 204) {
                    return;
                }
                // Handle "already exists" as a benign condition
                if (status === 409) {
                    console.warn(`${variableType} cluster variable "${variableName}" already exists (HTTP 409).`);
                    return;
                }
                bodyText = await response.text();
                lastErrorMessage = `HTTP ${status} - ${bodyText.slice(0, 200)}`;
                // Retry on transient gateway / upstream errors and on HTTP 500
                // (search backend not ready yet — observed on fresh OpenSearch deploys).
                if ((status === 500 || (status >= 502 && status <= 504)) &&
                    attempt < maxAttempts) {
                    console.warn(`createClusterVariable "${variableName}" attempt ${attempt}/${maxAttempts} got HTTP ${status}; retrying...`);
                    await new Promise((r) => setTimeout(r, baseDelayMs * attempt));
                    continue;
                }
            }
            catch (networkErr) {
                // Network-layer error (e.g. ECONNRESET while the gateway is
                // restarting). Retry a few times before giving up.
                lastErrorMessage =
                    networkErr instanceof Error ? networkErr.message : String(networkErr);
                if (attempt < maxAttempts) {
                    console.warn(`createClusterVariable "${variableName}" attempt ${attempt}/${maxAttempts} threw (${lastErrorMessage}); retrying...`);
                    await new Promise((r) => setTimeout(r, baseDelayMs * attempt));
                    continue;
                }
            }
            throw new Error(`Failed to create ${variableType} cluster variable "${variableName}": ${lastErrorMessage}`);
        }
    }
    catch (error) {
        if (error instanceof Error && error.message.includes('Failed to create')) {
            throw error;
        }
        // Wrap unexpected errors with context
        const errorMessage = error instanceof Error ? error.message : String(error);
        throw new Error(`Unexpected error creating ${variableType} cluster variable "${variableName}": ${errorMessage}`);
    }
}
async function createJsonClusterVariable(authToken, environment = 'saas', customVariableName, customVariableValue, clusterType) {
    const variableName = customVariableName ?? String(process.env.CLUSTER_VARIABLE_NAME);
    const variableValue = customVariableValue
        ? JSON.parse(customVariableValue)
        : JSON.parse(process.env.CLUSTER_VARIABLE_JSON);
    await createClusterVariableInternal(authToken ?? '', environment, variableName, variableValue, 'JSON', clusterType);
}
exports.createJsonClusterVariable = createJsonClusterVariable;
async function createStringClusterVariable(authToken, environment = 'saas', customVariableName, customVariableValue, clusterType) {
    const variableName = customVariableName ?? String(process.env.CLUSTER_VARIABLE_STRING_NAME);
    const variableValue = customVariableValue ?? process.env.CLUSTER_VARIABLE_STRING_VALUE;
    await createClusterVariableInternal(authToken ?? '', environment, variableName, variableValue, 'String', clusterType);
}
exports.createStringClusterVariable = createStringClusterVariable;
async function getOptimizeCoockie(page) {
    const optimizeUrl = process.env.CAMUNDA_OPTIMIZE_BASE_URL;
    const maxLoginAttempts = 3;
    // Auth0 can fail or rate-limit concurrent logins. Retry the whole flow if
    // loginToApp throws (e.g. waitForURL times out after a bad Auth0 redirect).
    for (let loginAttempt = 0; loginAttempt < maxLoginAttempts; loginAttempt++) {
        try {
            await page.goto('about:blank');
            await page.context().clearCookies();
            await (0, utils_1.loginToApp)(optimizeUrl, page);
            break;
        }
        catch (error) {
            if (loginAttempt < maxLoginAttempts - 1) {
                console.warn(`getOptimizeCoockie: login attempt ${loginAttempt + 1} failed, retrying after backoff...`, error);
                await page.goto('about:blank');
                await page.waitForTimeout(5000 * (loginAttempt + 1));
            }
            else {
                throw error;
            }
        }
    }
    const context = page.context();
    // Optimize sets its session cookies asynchronously after the Auth0 redirect.
    // Poll storage state until both cookies are present (up to ~30 s).
    let serviceTokenCookie;
    let authTokenCookie;
    for (let i = 0; i < 10; i++) {
        const tempFile = path_1.default.join(os_1.default.tmpdir(), `.auth_optimize_${Date.now()}_${Math.random().toString(36).slice(2)}`);
        await context.storageState({ path: tempFile });
        const authData = JSON.parse(fs_1.default.readFileSync(tempFile, 'utf8'));
        fs_1.default.unlinkSync(tempFile);
        serviceTokenCookie = authData.cookies.find((cookie) => cookie.name === 'X-Optimize-Service-Token_0');
        authTokenCookie = authData.cookies.find((cookie) => cookie.name === 'X-Optimize-Authorization_0');
        if (serviceTokenCookie?.value && authTokenCookie?.value) {
            break;
        }
        if (i < 9) {
            console.warn(`getOptimizeCoockie: cookies not ready yet (attempt ${i + 1}/10), retrying in 3 s...`);
            await page.waitForTimeout(3000);
        }
    }
    const optimizeServiceToken = serviceTokenCookie?.value || '';
    const optimizeAuthToken = authTokenCookie?.value || '';
    const optimizeCookie = `X-Optimize-Service-Token_0=${optimizeServiceToken}; X-Optimize-Authorization_0=${optimizeAuthToken}`;
    return optimizeCookie;
}
exports.getOptimizeCoockie = getOptimizeCoockie;
async function getOptimizeCookieSm(page) {
    const optimizeUrl = process.env.CAMUNDA_OPTIMIZE_BASE_URL;
    const username = 'demo';
    const password = process.env.DISTRO_QA_E2E_TESTS_IDENTITY_FIRSTUSER_PASSWORD;
    await page.goto(optimizeUrl, { timeout: 30000 });
    // Wait for login form and fill credentials (Keycloak login)
    await page.waitForSelector('#username', { timeout: 30000 });
    await page.fill('#username', username);
    await page.fill('#password', password);
    await page.click('button[type="submit"]');
    // Wait for redirect to Optimize after login
    await page.waitForURL(`${optimizeUrl}/**`, { timeout: 30000 });
    const context = page.context();
    await context.storageState({ path: path_1.default.join(__dirname, '.auth_optimize_sm') });
    const authData = JSON.parse(fs_1.default.readFileSync(path_1.default.join(__dirname, '.auth_optimize_sm'), 'utf8'));
    const serviceTokenCookie = authData.cookies.find((cookie) => cookie.name === 'X-Optimize-Service-Token_0');
    const authTokenCookie = authData.cookies.find((cookie) => cookie.name === 'X-Optimize-Authorization_0');
    const optimizeServiceToken = serviceTokenCookie?.value || '';
    const optimizeAuthToken = authTokenCookie?.value || '';
    const optimizeCookie = `X-Optimize-Service-Token_0=${optimizeServiceToken}; X-Optimize-Authorization_0=${optimizeAuthToken}`;
    return optimizeCookie;
}
exports.getOptimizeCookieSm = getOptimizeCookieSm;
async function createCollection(request, options) {
    const optimizeResponse = await request.post(`${process.env.CAMUNDA_OPTIMIZE_BASE_URL}/api/collection`, {
        headers: {
            Cookie: options.optimizeCookie,
        },
        data: {
            name: options.name,
        },
    });
    await assertResponseStatus(optimizeResponse, 200);
    const optimizeResponseBody = await optimizeResponse.json();
    return optimizeResponseBody.id;
}
exports.createCollection = createCollection;
async function createDashboard(request, options) {
    const optimizeResponse = await request.post(`${process.env.CAMUNDA_OPTIMIZE_BASE_URL}/api/dashboard`, {
        headers: {
            Cookie: options.optimizeCookie,
        },
        data: {
            collectionId: options.collectionId,
            name: options.name,
            description: null,
            tiles: [],
            availableFilters: [],
            refreshRateSeconds: null,
        },
    });
    await assertResponseStatus(optimizeResponse, 200);
    const responseBody = await optimizeResponse.json();
    if (!responseBody?.id) {
        throw new Error(`Expected dashboard ID in response, but got: ${JSON.stringify(responseBody, null, 2)}`);
    }
    return responseBody.id;
}
exports.createDashboard = createDashboard;
async function createSingleProcessReport(request, options) {
    // Default configuration (can be overridden)
    const defaultConfiguration = {
        color: '#1991c8',
        aggregationTypes: [{ type: 'avg', value: null }],
        userTaskDurationTimes: ['total'],
        alwaysShowAbsolute: false,
        alwaysShowRelative: false,
        customBucket: {
            active: false,
            bucketSize: '10',
            bucketSizeUnit: 'minute',
            baseline: '0',
            baselineUnit: 'minute',
        },
        distributeByCustomBucket: {
            active: false,
            bucketSize: '10',
            bucketSizeUnit: 'minute',
            baseline: '0',
            baselineUnit: 'minute',
        },
        distributeByDateVariableUnit: 'automatic',
        groupByDateVariableUnit: 'automatic',
        heatmapTargetValue: { active: false, values: {} },
        hideAbsoluteValue: false,
        hideRelativeValue: false,
        horizontalBar: false,
        logScale: false,
        measureVisualizations: { frequency: 'bar', duration: 'line' },
        pointMarkers: true,
        precision: null,
        processPart: null,
        showGradientBars: true,
        showInstanceCount: false,
        sorting: null,
        stackedBar: false,
        tableColumns: {
            includeNewVariables: false,
            includedColumns: [],
            excludedColumns: [],
            columnOrder: [],
        },
        targetValue: { active: false, isKpi: false },
        xlabel: '',
        ylabel: '',
        xml: '',
        definitions: options.definitions || [],
        visualization: null,
        description: options.description || null,
    };
    const payload = {
        collectionId: options.collectionId,
        name: options.name,
        description: options.description || null,
        data: {},
        configuration: options.configuration || defaultConfiguration,
    };
    const response = await request.post(`${process.env.CAMUNDA_OPTIMIZE_BASE_URL}/api/report/process/single`, {
        headers: {
            Cookie: options.optimizeCookie,
            'Content-Type': 'application/json',
        },
        data: payload,
    });
    await assertResponseStatus(response, 200);
    const responseBody = await response.json();
    if (!responseBody?.id) {
        throw new Error(`Expected report ID in response, but got: ${JSON.stringify(responseBody, null, 2)}`);
    }
    return responseBody.id;
}
exports.createSingleProcessReport = createSingleProcessReport;
async function updateCollectionScope(request, options) {
    const url = `${process.env.CAMUNDA_OPTIMIZE_BASE_URL}/api/collection/${options.collectionId}/scope`;
    const response = await request.put(url, {
        headers: {
            Cookie: options.optimizeCookie,
            'Content-Type': 'application/json',
        },
        data: options.data,
    });
    await assertResponseStatus(response, 200);
    let responseBody = null;
    try {
        responseBody = await response.json();
    }
    catch (err) {
        responseBody = null;
    }
    return responseBody;
}
exports.updateCollectionScope = updateCollectionScope;
