var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import ComponentCode from "../ComponentCode";
import BadDataException from "../../../../Types/Exception/BadDataException";
import ObjectID from "../../../../Types/ObjectID";
import ComponentID from "../../../../Types/Workflow/ComponentID";
import WorkflowComponents from "../../../../Types/Workflow/Components/Workflow";
import CaptureSpan from "../../../Utils/Telemetry/CaptureSpan";
export default class ExecuteWorkflow extends ComponentCode {
    constructor() {
        super();
        const Component = WorkflowComponents.find((i) => {
            return i.id === ComponentID.WorkflowRun;
        });
        if (!Component) {
            throw new BadDataException("Execute Workflow component not found.");
        }
        this.setMetadata(Component);
    }
    async run(args, options) {
        const successPort = this.getMetadata().outPorts.find((p) => {
            return p.id === "out";
        });
        const errorPort = this.getMetadata().outPorts.find((p) => {
            return p.id === "error";
        });
        if (!successPort) {
            throw options.onError(new BadDataException("Out port not found"));
        }
        if (!errorPort) {
            throw options.onError(new BadDataException("Error port not found"));
        }
        try {
            const workflowIdString = args["workflowId"];
            if (!workflowIdString) {
                throw new BadDataException("Workflow ID is required.");
            }
            if (!ObjectID.isValidUUID(workflowIdString)) {
                throw new BadDataException("Workflow ID is not a valid ObjectID: " + workflowIdString);
            }
            const targetWorkflowId = new ObjectID(workflowIdString);
            // Prevent a workflow from triggering itself — obvious infinite loop.
            if (targetWorkflowId.toString() === options.workflowId.toString()) {
                throw new BadDataException("A workflow cannot execute itself. Use a different workflow ID.");
            }
            let payload = {};
            const rawArgs = args["arguments"];
            if (rawArgs) {
                if (typeof rawArgs === "object") {
                    payload = rawArgs;
                }
                else if (typeof rawArgs === "string") {
                    try {
                        payload = JSON.parse(rawArgs);
                    }
                    catch (err) {
                        throw new BadDataException("Arguments must be valid JSON: " +
                            (err instanceof Error ? err.message : String(err)));
                    }
                }
                else {
                    throw new BadDataException("Arguments must be a JSON object or a JSON string.");
                }
            }
            options.log("Enqueuing child workflow " + targetWorkflowId.toString());
            options.log("Payload:");
            options.log(payload);
            await options.executeWorkflow({
                workflowId: targetWorkflowId,
                returnValues: payload,
            });
            options.log("Child workflow " +
                targetWorkflowId.toString() +
                " enqueued successfully.");
            return {
                returnValues: {},
                executePort: successPort,
            };
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            options.log("Failed to execute child workflow: " + message);
            return {
                returnValues: {
                    error: message,
                },
                executePort: errorPort,
            };
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", Promise)
], ExecuteWorkflow.prototype, "run", null);
//# sourceMappingURL=Workflow.js.map