"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendHttpRequestExecutor = void 0;
const toolExecutor_types_1 = require("../toolExecutor-types");
const SendHttpRequestStep_1 = __importDefault(require("../../sharedUtils/mablscript/canonical/SendHttpRequestStep"));
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const variable_constants_1 = require("../../sharedUtils/variable-constants");
const mablApi_1 = require("../../../mablApi");
exports.sendHttpRequestExecutor = {
    needsFind: () => false,
    getStepType: () => mablApi_1.ExecuteToolName.SendHttpRequest,
    execute: async (payload, stateProvider, eventHandler, logger) => {
        const toolParams = payload.toolCall
            .toolParams;
        if (!toolParams?.request?.url || !toolParams?.request?.method) {
            logger.error('SendHttpRequest executor requires request.url and request.method');
            return {
                success: false,
                errorMessage: 'request.url and request.method are required',
            };
        }
        const request = {
            url: toolParams.request.url,
            method: toolParams.request.method,
        };
        if (toolParams.request.headers !== undefined) {
            request.headers = toolParams.request.headers;
        }
        if (toolParams.request.authorization !== undefined) {
            const authView = toolParams.request.authorization;
            if (authView.type !== 'basic' && authView.type !== 'bearer') {
                return {
                    success: false,
                    errorMessage: `Invalid authorization 'type' value '${String(authView.type)}'. Use 'basic' (with username + password) or 'bearer' (with token).`,
                };
            }
            if (authView.type === 'basic') {
                const username = authView.properties?.username;
                const password = authView.properties?.password;
                if (typeof username !== 'string' || typeof password !== 'string') {
                    return {
                        success: false,
                        errorMessage: "When authorization.type='basic', both properties.username and properties.password are required.",
                    };
                }
                const basic = {
                    type: 'basic',
                    properties: { username, password },
                };
                request.authorization = basic;
            }
            else {
                const token = authView.properties?.token;
                if (typeof token !== 'string') {
                    return {
                        success: false,
                        errorMessage: "When authorization.type='bearer', properties.token is required.",
                    };
                }
                const bearer = {
                    type: 'bearer',
                    properties: { token },
                };
                request.authorization = bearer;
            }
        }
        if (toolParams.request.body !== undefined) {
            request.body = toolParams.request.body;
        }
        const responseAssertions = toolParams.assertions?.map(({ source, target, assertion, value }) => {
            const scrubbedTarget = target?.trim() || undefined;
            return {
                source: source,
                target: scrubbedTarget,
                assertion: assertion,
                value,
            };
        });
        const responseVariables = toolParams.variables?.map(({ source, target, name }) => {
            const scrubbedTarget = target?.trim() || undefined;
            return {
                source: source,
                target: scrubbedTarget,
                name,
            };
        });
        const advancedOptions = toolParams.options !== undefined ? { ...toolParams.options } : undefined;
        const variables = (toolParams.variables ?? []).map(({ name }) => {
            const recordedVariable = {
                name: `user.${name}`,
                humanizedName: name,
                variableType: mablscriptFind_1.VariableType.API,
                value: variable_constants_1.EMPTY_VARIABLE_VALUE_PLACEHOLDER,
            };
            eventHandler.saveVariable(recordedVariable);
            return recordedVariable;
        });
        const step = SendHttpRequestStep_1.default.create({
            request,
            responseAssertions,
            responseVariables,
            advancedOptions,
            response: undefined,
            variables,
        });
        return (0, toolExecutor_types_1.recordStepAndTrackResult)(() => Promise.resolve({ steps: [step], stepsToReplay: 1, step }), 0, stateProvider, eventHandler, logger);
    },
};
