"use strict";
/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
 * one or more contributor license agreements. See the NOTICE file distributed
 * with this work for additional information regarding copyright ownership.
 * Licensed under the Camunda License 1.0. You may not use this file
 * except in compliance with the Camunda License 1.0.
 */
Object.defineProperty(exports, "__esModule", { value: true });
/*
 * Full end-to-end flow tests for /mcp/processes.
 * Deploy a process, discover via tools/list, invoke via tools/call, verify in Operate.
 */
const _8_10_1 = require("../../../../fixtures/8.10");
const test_1 = require("@playwright/test");
const apiHelpers_1 = require("../../../../utils/apiHelpers");
const constants_1 = require("../../../../utils/constants");
const mcpHelpers_1 = require("../../../../utils/mcpHelpers");
let authToken;
let mcpProcessesUrl;
let messageSubscriptionsSearchUrl;
let processInstancesSearchUrl;
let mcpSessionId = null;
_8_10_1.test.describe.configure({ mode: 'parallel' });
_8_10_1.test.describe('Orchestration Cluster MCP Server — /mcp/processes full E2E flows', () => {
    _8_10_1.test.beforeAll(async () => {
        authToken = await (0, apiHelpers_1.authSaasAPI)(undefined, 'agentic_cluster');
        mcpProcessesUrl = (0, apiHelpers_1.buildZeebeApiUrl)('/mcp/processes', 'saas', 'agentic_cluster');
        messageSubscriptionsSearchUrl = (0, apiHelpers_1.buildZeebeApiUrl)('/v2/message-subscriptions/search', 'saas', 'agentic_cluster');
        processInstancesSearchUrl = (0, apiHelpers_1.buildZeebeApiUrl)('/v2/process-instances/search', 'saas', 'agentic_cluster');
        const apiContext = await (0, apiHelpers_1.getApiRequestContext)();
        mcpSessionId = await (0, mcpHelpers_1.initializeMcpSession)(apiContext, mcpProcessesUrl, authToken, mcpSessionId);
    });
    (0, _8_10_1.test)('SC-E2E-01 — Complete flow: deploy → discover via subscriptions → invoke via tools/call → verify instance in Operate', async () => {
        const apiContext = await (0, apiHelpers_1.getApiRequestContext)();
        let subscriptionKey = null;
        let processInstanceKey = null;
        await _8_10_1.test.step('Deploy process', async () => {
            const processKey = await (0, apiHelpers_1.deployProcess)('./resources/mcp_server_saas/mcp_as_tool_process.bpmn', authToken, 'saas', 'agentic_cluster');
            (0, test_1.expect)(processKey).not.toBeNull();
        });
        await _8_10_1.test.step('Discover tool via message-subscriptions search', async () => {
            await (0, test_1.expect)(async () => {
                const res = await apiContext.post(messageSubscriptionsSearchUrl, {
                    headers: (0, mcpHelpers_1.buildMcpHeaders)(authToken, mcpSessionId),
                    data: {
                        filter: {
                            processDefinitionId: 'mcpAsToolProcess',
                            messageSubscriptionType: 'START_EVENT',
                        },
                        sort: [{ field: 'processDefinitionVersion', order: 'desc' }],
                        page: { limit: 1 },
                    },
                });
                await (0, mcpHelpers_1.assertResponseStatus)(res, 200);
                const json = (await res.json());
                (0, test_1.expect)(json.items.length).toBeGreaterThanOrEqual(1);
                subscriptionKey = String(json.items[0].messageSubscriptionKey);
            }).toPass(constants_1.defaultAssertionOptions);
        });
        const expectedToolName = `mcp-as-tool-process_${subscriptionKey}`;
        await _8_10_1.test.step('Confirm tool appears in tools/list', async () => {
            await (0, test_1.expect)(async () => {
                const tools = await (0, mcpHelpers_1.listTools)(apiContext, mcpProcessesUrl, authToken, mcpSessionId);
                (0, test_1.expect)(tools.some((t) => t.name === expectedToolName)).toBe(true);
            }).toPass(constants_1.defaultAssertionOptions);
        });
        await _8_10_1.test.step('Invoke tool via tools/call', async () => {
            const body = await (0, mcpHelpers_1.callTool)(apiContext, mcpProcessesUrl, authToken, mcpSessionId, expectedToolName, {});
            (0, test_1.expect)(body.result).toBeDefined();
            (0, test_1.expect)(body.result.isError).not.toBe(true);
            const text = body.result.content[0]?.text ?? '';
            processInstanceKey = (0, mcpHelpers_1.extractProcessInstanceKey)(text);
            (0, test_1.expect)(processInstanceKey, `Expected processInstanceKey in tools/call result, got: ${text}`).not.toBeNull();
        });
        await _8_10_1.test.step('Verify process instance visible in Operate', async () => {
            await (0, test_1.expect)(async () => {
                const searchRes = await apiContext.post(processInstancesSearchUrl, {
                    headers: (0, mcpHelpers_1.buildMcpHeaders)(authToken, mcpSessionId),
                    data: { filter: { processInstanceKey } },
                });
                await (0, mcpHelpers_1.assertResponseStatus)(searchRes, 200);
                const searchJson = (await searchRes.json());
                (0, test_1.expect)(searchJson.items.length).toBeGreaterThanOrEqual(1);
                (0, test_1.expect)(searchJson.items[0].processInstanceKey).toBe(processInstanceKey);
            }).toPass(constants_1.defaultAssertionOptions);
        });
    });
    (0, _8_10_1.test)('SC-E2E-03 — Redeploying a process supersedes the old subscription; the new tool is discoverable and callable', async () => {
        // Intra-process redeployment: new version supersedes the previous message
        // subscription, so v1 disappears from tools/list and v2 takes its place.
        const apiContext = await (0, apiHelpers_1.getApiRequestContext)();
        let v1SubscriptionKey = null;
        let v2ToolName = null;
        await _8_10_1.test.step('Deploy v1 of mcpE2EFlowTool', async () => {
            const v1Key = await (0, apiHelpers_1.deployProcess)('./resources/mcp_server_saas/mcp_e2e_v1.bpmn', authToken, 'saas', 'agentic_cluster');
            if (v1Key == null)
                throw new Error('Failed to deploy mcp_e2e_v1.bpmn');
        });
        await _8_10_1.test.step('Wait for v1 subscription and capture key', async () => {
            await (0, test_1.expect)(async () => {
                const res = await apiContext.post(messageSubscriptionsSearchUrl, {
                    headers: (0, mcpHelpers_1.buildMcpHeaders)(authToken, mcpSessionId),
                    data: {
                        filter: {
                            processDefinitionId: 'mcpE2EFlowTool',
                            messageSubscriptionType: 'START_EVENT',
                        },
                        sort: [{ field: 'processDefinitionVersion', order: 'desc' }],
                        page: { limit: 1 },
                    },
                });
                await (0, mcpHelpers_1.assertResponseStatus)(res, 200);
                const json = (await res.json());
                (0, test_1.expect)(json.items.length).toBeGreaterThanOrEqual(1);
                v1SubscriptionKey = String(json.items[0].messageSubscriptionKey);
            }).toPass(constants_1.defaultAssertionOptions);
        });
        const v1ToolName = `mcp-e2e-flow-tool_${v1SubscriptionKey}`;
        await _8_10_1.test.step('Confirm v1 tool appears in tools/list', async () => {
            await (0, test_1.expect)(async () => {
                const tools = await (0, mcpHelpers_1.listTools)(apiContext, mcpProcessesUrl, authToken, mcpSessionId);
                (0, test_1.expect)(tools.some((t) => t.name === v1ToolName)).toBe(true);
            }).toPass(constants_1.defaultAssertionOptions);
        });
        await _8_10_1.test.step('Deploy v2 of mcpE2EFlowTool', async () => {
            const v2Key = await (0, apiHelpers_1.deployProcess)('./resources/mcp_server_saas/mcp_e2e_v2.bpmn', authToken, 'saas', 'agentic_cluster');
            if (v2Key == null)
                throw new Error('Failed to deploy mcp_e2e_v2.bpmn');
        });
        await _8_10_1.test.step('Wait for v1 subscription to be superseded and v2 tool to appear', async () => {
            await (0, test_1.expect)(async () => {
                const tools = await (0, mcpHelpers_1.listTools)(apiContext, mcpProcessesUrl, authToken, mcpSessionId);
                const toolNames = tools.map((t) => t.name);
                (0, test_1.expect)(toolNames).not.toContain(v1ToolName);
                const newTool = tools.find((t) => /^mcp-e2e-flow-tool_\d+$/.test(t.name) && t.name !== v1ToolName);
                (0, test_1.expect)(newTool).toBeDefined();
                v2ToolName = newTool.name;
            }).toPass(constants_1.deletionAssertionOptions);
        });
        (0, test_1.expect)(v2ToolName).not.toBe(v1ToolName);
        await _8_10_1.test.step('Invoke v2 tool and assert it starts a process instance', async () => {
            const body = await (0, mcpHelpers_1.callTool)(apiContext, mcpProcessesUrl, authToken, mcpSessionId, v2ToolName, {});
            (0, test_1.expect)(body.result).toBeDefined();
            (0, test_1.expect)(body.result.isError, `Expected v2 tool ${v2ToolName} to be callable, got: ${JSON.stringify(body)}`).not.toBe(true);
            const text = body.result.content[0]?.text ?? '';
            const pik = (0, mcpHelpers_1.extractProcessInstanceKey)(text);
            (0, test_1.expect)(pik, `Expected processInstanceKey in v2 tool result, got: ${text}`).not.toBeNull();
        });
    });
});
