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 Response from "../../../Utils/Response";
import TriggerCode from "../TriggerCode";
import BadDataException from "../../../../Types/Exception/BadDataException";
import ObjectID from "../../../../Types/ObjectID";
import ComponentID from "../../../../Types/Workflow/ComponentID";
import WebhookComponents from "../../../../Types/Workflow/Components/Webhook";
import CaptureSpan from "../../../Utils/Telemetry/CaptureSpan";
import WorkflowService from "../../../Services/WorkflowService";
export default class WebhookTrigger extends TriggerCode {
    constructor() {
        super();
        const WebhookComponent = WebhookComponents.find((i) => {
            return i.id === ComponentID.Webhook;
        });
        if (!WebhookComponent) {
            throw new BadDataException("Webhook trigger not found.");
        }
        this.setMetadata(WebhookComponent);
    }
    async run(args, options) {
        const successPort = this.getMetadata().outPorts.find((p) => {
            return p.id === "out";
        });
        if (!successPort) {
            throw options.onError(new BadDataException("Out port not found"));
        }
        return {
            returnValues: Object.assign({}, args),
            executePort: successPort,
        };
    }
    async init(props) {
        props.router.get(`/trigger/:secretkey`, async (req, res, next) => {
            try {
                await this.initTrigger(req, res, props);
            }
            catch (e) {
                return next(e);
            }
        });
        props.router.post(`/trigger/:secretkey`, async (req, res, next) => {
            try {
                await this.initTrigger(req, res, props);
            }
            catch (e) {
                return next(e);
            }
        });
    }
    async initTrigger(req, res, props) {
        const secretKey = req.params["secretkey"];
        if (!secretKey) {
            throw new BadDataException("Secret key is required to trigger workflow.");
        }
        // Look up the workflow by webhook secret key.
        const workflow = await WorkflowService.findOneBy({
            query: {
                webhookSecretKey: secretKey,
            },
            select: {
                _id: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!workflow || !workflow._id) {
            throw new BadDataException("Workflow not found for the provided secret key.");
        }
        const executeWorkflow = {
            workflowId: new ObjectID(workflow._id),
            returnValues: {
                "request-headers": req.headers,
                "request-params": req.query,
                "request-body": req.body,
            },
        };
        await props.executeWorkflow(executeWorkflow);
        Response.sendJsonObjectResponse(req, res, { status: "Scheduled" });
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", Promise)
], WebhookTrigger.prototype, "run", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], WebhookTrigger.prototype, "init", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Object]),
    __metadata("design:returntype", Promise)
], WebhookTrigger.prototype, "initTrigger", null);
//# sourceMappingURL=Webhook.js.map