var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var RequestInterceptionTrigger_exports = {};
__export(RequestInterceptionTrigger_exports, {
  RequestInterceptionTrigger: () => RequestInterceptionTrigger
});
module.exports = __toCommonJS(RequestInterceptionTrigger_exports);
var import_data_source = require("@tachybase/data-source");
var import_module_error_handler = __toESM(require("@tachybase/module-error-handler"));
var import_constants = require("../../constants");
var import_triggers = __toESM(require("../../triggers"));
class RequestInterceptionError extends Error {
  constructor(message) {
    super(message);
    this.status = 400;
    this.messages = [];
    this.name = "RequestInterceptionError";
  }
}
const _RequestInterceptionTrigger = class _RequestInterceptionTrigger extends import_triggers.default {
  constructor(workflow) {
    super(workflow);
    this.sync = true;
    this.middleware = async (context, next) => {
      const {
        resourceName,
        actionName,
        params: { filterByTk, filter, values, triggerWorkflows = "" }
      } = context.action;
      const dataSourceHeader = context.get("x-data-source");
      const jointCollectionName = (0, import_data_source.joinCollectionName)(dataSourceHeader, resourceName);
      const triggerWorkflowsMap = /* @__PURE__ */ new Map();
      const triggerWorkflowsArray = [];
      for (const trigger of triggerWorkflows.split(",")) {
        const [key, path] = trigger.split("!");
        triggerWorkflowsMap.set(key, path);
        triggerWorkflowsArray.push(key);
      }
      const workflows = Array.from(this.workflow.enabledCache.values()).filter(
        (item) => item.type === _RequestInterceptionTrigger.TYPE && item.config.collection === jointCollectionName
      );
      const globalWorkflows = workflows.filter((item) => {
        var _a;
        return item.config.global && ((_a = item.config.actions) == null ? void 0 : _a.includes(actionName));
      }).sort((a, b) => a.id - b.id);
      const localWorkflows = workflows.filter((item) => !item.config.global).sort((a, b) => {
        const aIndex = triggerWorkflowsArray.indexOf(a.key);
        const bIndex = triggerWorkflowsArray.indexOf(b.key);
        if (aIndex === -1 && bIndex === -1) {
          return a.id - b.id;
        }
        if (aIndex === -1) {
          return 1;
        }
        if (bIndex === -1) {
          return -1;
        }
        return aIndex - bIndex;
      });
      for (const workflow of localWorkflows.concat(globalWorkflows)) {
        if (!workflow.config.global && !triggerWorkflowsMap.has(workflow.key)) {
          continue;
        }
        const processor = await this.workflow.trigger(
          workflow,
          {
            user: context.state.currentUser,
            roleName: context.state.currentRole,
            params: {
              filterByTk,
              filter,
              values
            }
          },
          { httpContext: context }
        );
        if (!processor) {
          return context.throw(500);
        }
        const { lastSavedJob, nodesMap } = processor;
        const lastNode = nodesMap.get(lastSavedJob == null ? void 0 : lastSavedJob.nodeId);
        if (processor.execution.status === import_constants.EXECUTION_STATUS.RESOLVED) {
          if ((lastNode == null ? void 0 : lastNode.type) === "end") {
            return;
          }
          continue;
        }
        if (processor.execution.status < import_constants.EXECUTION_STATUS.STARTED) {
          if ((lastNode == null ? void 0 : lastNode.type) !== "end") {
            return context.throw(
              500,
              context.t("Workflow on your action failed, please contact the administrator", { ns: "workflow" })
            );
          }
          const err = new RequestInterceptionError("Request is intercepted by workflow");
          err.status = 400;
          err.messages = context.state.messages;
          return context.throw(err.status, err);
        }
        return context.throw(500, "Workflow on your action hangs, please contact the administrator");
      }
      await next();
    };
    workflow.app.use(this.middleware, { tag: "workflowFilter", after: "dataSource" });
    workflow.app.pm.get(import_module_error_handler.default).errorHandler.register(
      (err) => err instanceof RequestInterceptionError,
      async (err, ctx) => {
        ctx.body = {
          errors: err.messages
        };
        ctx.status = err.status;
      }
    );
  }
  on() {
  }
  off() {
  }
};
_RequestInterceptionTrigger.TYPE = "request-interception";
let RequestInterceptionTrigger = _RequestInterceptionTrigger;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  RequestInterceptionTrigger
});
