"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const scriptController = require("../../api/controllers/script");
const { buildCtx } = require("./utils");
const automationUtils = require("../automationUtils");
exports.definition = {
    name: "JS Scripting",
    tagline: "Execute JavaScript Code",
    icon: "Code",
    description: "Run a piece of JavaScript code in your automation",
    type: "ACTION",
    internal: true,
    stepId: "EXECUTE_SCRIPT",
    inputs: {},
    schema: {
        inputs: {
            properties: {
                code: {
                    type: "string",
                    customType: "code",
                    title: "Code",
                },
            },
            required: ["code"],
        },
        outputs: {
            properties: {
                value: {
                    type: "string",
                    description: "The result of the return statement",
                },
                success: {
                    type: "boolean",
                    description: "Whether the action was successful",
                },
            },
        },
        required: ["success"],
    },
};
exports.run = function ({ inputs, appId, context, emitter }) {
    return __awaiter(this, void 0, void 0, function* () {
        if (inputs.code == null) {
            return {
                success: false,
                response: {
                    message: "Invalid inputs",
                },
            };
        }
        const ctx = buildCtx(appId, emitter, {
            body: {
                script: inputs.code,
                context,
            },
        });
        try {
            yield scriptController.execute(ctx);
            return {
                success: true,
                value: ctx.body,
            };
        }
        catch (err) {
            return {
                success: false,
                response: automationUtils.getError(err),
            };
        }
    });
};
