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 { WorkflowHostname } from "../EnvironmentConfig";
import ClusterKeyAuthorization from "../Middleware/ClusterKeyAuthorization";
import DatabaseService from "./DatabaseService";
import WorkflowLabelRuleEngineService from "./WorkflowLabelRuleEngineService";
import WorkflowOwnerRuleEngineService from "./WorkflowOwnerRuleEngineService";
import Protocol from "../../Types/API/Protocol";
import Route from "../../Types/API/Route";
import URL from "../../Types/API/URL";
import ObjectID from "../../Types/ObjectID";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import { ComponentType, NodeType, } from "../../Types/Workflow/Component";
import API from "../../Utils/API";
import Model from "../../Models/DatabaseModels/Workflow";
import logger from "../Utils/Logger";
import UUID from "../../Utils/UUID";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onCreateSuccess(_onCreate, createdItem) {
        // Auto-generate webhook secret key for new workflows.
        if (!createdItem.webhookSecretKey && createdItem._id) {
            const secretKey = UUID.generate();
            await this.updateOneById({
                id: new ObjectID(createdItem._id),
                data: {
                    webhookSecretKey: secretKey,
                },
                props: {
                    isRoot: true,
                    ignoreHooks: true,
                },
            });
            createdItem.webhookSecretKey = secretKey;
        }
        if (createdItem.projectId && createdItem.id) {
            /*
             * Run label rule first so rule-added labels are persisted before
             * owner rules run. Owner rules re-fetch labels, so this lets owner
             * rules key on rule-added labels.
             */
            Promise.resolve()
                .then(async () => {
                await WorkflowLabelRuleEngineService.applyRulesToWorkflow(createdItem);
            })
                .then(async () => {
                await WorkflowOwnerRuleEngineService.applyRulesToWorkflow(createdItem);
            })
                .catch((error) => {
                var _a, _b;
                logger.error(`Error applying workflow rules in WorkflowService.onCreateSuccess: ${error}`, {
                    projectId: (_a = createdItem.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                    workflowId: (_b = createdItem.id) === null || _b === void 0 ? void 0 : _b.toString(),
                });
            });
        }
        return createdItem;
    }
    async onUpdateSuccess(onUpdate, _updatedItemIds) {
        /// save trigger and trigger args.
        var _a, _b;
        if (onUpdate.updateBy.data &&
            onUpdate.updateBy.data.graph &&
            onUpdate.updateBy.data.graph["nodes"]) {
            let trigger = null;
            // check if it has a trigger node.
            for (const node of onUpdate.updateBy.data.graph["nodes"]) {
                const nodeData = node["data"];
                if (nodeData.componentType === ComponentType.Trigger &&
                    nodeData.nodeType === NodeType.Node) {
                    // found the trigger;
                    trigger = nodeData;
                }
            }
            await this.updateOneById({
                id: new ObjectID(onUpdate.updateBy.query._id),
                data: {
                    triggerId: (trigger === null || trigger === void 0 ? void 0 : trigger.metadataId) || null,
                    triggerArguments: (trigger === null || trigger === void 0 ? void 0 : trigger.arguments) || {},
                },
                props: {
                    isRoot: true,
                    ignoreHooks: true,
                },
            });
        }
        logger.debug("Updating workflow on the workflow service", {
            workflowId: (_a = onUpdate.updateBy.query._id) === null || _a === void 0 ? void 0 : _a.toString(),
        });
        await API.post({
            url: new URL(Protocol.HTTP, WorkflowHostname, new Route("/workflow/update/" + onUpdate.updateBy.query._id)),
            data: {},
            headers: Object.assign({}, ClusterKeyAuthorization.getClusterKeyHeaders()),
        });
        logger.debug("Updated workflow on the workflow service", {
            workflowId: (_b = onUpdate.updateBy.query._id) === null || _b === void 0 ? void 0 : _b.toString(),
        });
        return onUpdate;
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Model]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onCreateSuccess", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Array]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onUpdateSuccess", null);
export default new Service();
//# sourceMappingURL=WorkflowService.js.map