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 workflows_exports = {};
__export(workflows_exports, {
  destroy: () => destroy,
  dump: () => dump,
  load: () => load,
  moveWorkflow: () => moveWorkflow,
  retry: () => retry,
  revision: () => revision,
  sync: () => sync,
  test: () => test,
  trigger: () => trigger,
  update: () => update
});
module.exports = __toCommonJS(workflows_exports);
var import_actions = __toESM(require("@tachybase/actions"));
var import_database = require("@tachybase/database");
var import_Plugin = __toESM(require("../Plugin"));
async function update(context, next) {
  const repository = import_actions.utils.getRepositoryFromParams(context);
  const { filterByTk, values } = context.action.params;
  context.action.mergeParams({
    whitelist: [
      "title",
      "description",
      "enabled",
      "triggerTitle",
      "config",
      "options",
      "type",
      "sync",
      "category",
      // TODO: 这里的 icon 和 color 是审批插件的特有字段，后续办法是在审批里覆盖这个方法, 以便分离扩展字段和核心字段
      "color",
      "icon"
    ]
  });
  if (Object.keys(values).includes("config")) {
    const workflow = await repository.findById(filterByTk);
    if (workflow.get("executed")) {
      return context.throw(400, "config of executed workflow can not be updated");
    }
  }
  return import_actions.default.update(context, next);
}
async function destroy(context, next) {
  const repository = import_actions.utils.getRepositoryFromParams(context);
  const { filterByTk, filter } = context.action.params;
  await context.db.sequelize.transaction(async (transaction) => {
    const items = await repository.find({
      filterByTk,
      filter,
      fields: ["id", "key", "current"],
      transaction
    });
    const ids = new Set(items.map((item) => item.id));
    const keysSet = new Set(items.filter((item) => item.current).map((item) => item.key));
    const revisions = await repository.find({
      filter: {
        key: Array.from(keysSet),
        current: { [import_database.Op.not]: true }
      },
      fields: ["id"],
      transaction
    });
    revisions.forEach((item) => ids.add(item.id));
    context.body = await repository.destroy({
      filterByTk: Array.from(ids),
      individualHooks: true,
      transaction
    });
  });
  next();
}
async function dump(context, next) {
  const repository = import_actions.utils.getRepositoryFromParams(context);
  const { filterByTk, filter = {}, values = {} } = context.action.params;
  context.body = await context.db.sequelize.transaction(async (transaction) => {
    const origin = await repository.findOne({
      filterByTk,
      filter,
      appends: ["nodes"],
      context,
      transaction
    });
    const revisionData = filter.key ? {
      key: filter.key,
      title: origin.title,
      triggerTitle: origin.triggerTitle,
      allExecuted: origin.allExecuted,
      sync: origin.sync,
      initAt: origin.initAt
    } : values;
    const dumpOne = {
      ...origin.toJSON(),
      ...revisionData
    };
    return dumpOne;
  });
  await next();
}
async function load(context, next) {
  const plugin = context.app.getPlugin(import_Plugin.default);
  const repository = import_actions.utils.getRepositoryFromParams(context);
  const { values = {} } = context.action.params;
  context.body = await context.db.sequelize.transaction(async (transaction) => {
    const origin = values.workflow;
    const trigger2 = plugin.triggers.get(origin.type);
    const instance = await repository.create({
      values: {
        title: values.title,
        description: origin.description,
        type: origin.type,
        triggerTitle: origin.triggerTitle,
        allExecuted: origin.allExecuted,
        sync: origin.sync,
        initAt: origin.initAt,
        config: typeof trigger2.duplicateConfig === "function" ? await trigger2.duplicateConfig(origin, { transaction }) : origin.config
      },
      transaction
    });
    const originalNodesMap = /* @__PURE__ */ new Map();
    origin.nodes.forEach((node) => {
      originalNodesMap.set(node.id, node);
    });
    const oldToNew = /* @__PURE__ */ new Map();
    const newToOld = /* @__PURE__ */ new Map();
    for await (const node of origin.nodes) {
      const instruction = plugin.instructions.get(node.type);
      const newNode = await instance.createNode(
        {
          type: node.type,
          key: node.key,
          config: typeof instruction.duplicateConfig === "function" ? await instruction.duplicateConfig(node, { transaction }) : node.config,
          title: node.title,
          branchIndex: node.branchIndex
        },
        { transaction }
      );
      oldToNew.set(node.id, newNode);
      newToOld.set(newNode.id, node);
    }
    for await (const [oldId, newNode] of oldToNew.entries()) {
      const oldNode = originalNodesMap.get(oldId);
      const newUpstream = oldNode.upstreamId ? oldToNew.get(oldNode.upstreamId) : null;
      const newDownstream = oldNode.downstreamId ? oldToNew.get(oldNode.downstreamId) : null;
      await newNode.update(
        {
          upstreamId: (newUpstream == null ? void 0 : newUpstream.id) ?? null,
          downstreamId: (newDownstream == null ? void 0 : newDownstream.id) ?? null
        },
        { transaction }
      );
    }
    return instance;
  });
  await next();
}
async function test(context, next) {
  const plugin = context.app.getPlugin(import_Plugin.default);
  const repository = import_actions.utils.getRepositoryFromParams(context);
  const { filterByTk, filter = {}, values = {} } = context.action.params;
  if (!context.state) {
    context.state = {};
  }
  if (!context.state.messages) {
    context.state.messages = [];
  }
  const workflow = await repository.findOne({
    filterByTk,
    filter,
    appends: ["nodes"],
    context
  });
  const result = await plugin.trigger(
    workflow,
    {
      data: values.data,
      user: context.state.currentUser
    },
    { httpContext: context }
  );
  context.app.logger.info(result);
  context.state.messages.push({ message: "testing" });
  context.body = "here???";
}
async function revision(context, next) {
  const plugin = context.app.getPlugin(import_Plugin.default);
  const repository = import_actions.utils.getRepositoryFromParams(context);
  const { filterByTk, filter = {}, values = {} } = context.action.params;
  context.body = await context.db.sequelize.transaction(async (transaction) => {
    const origin = await repository.findOne({
      filterByTk,
      filter,
      appends: ["nodes"],
      context,
      transaction
    });
    const trigger2 = plugin.triggers.get(origin.type);
    const revisionData = filter.key ? {
      key: filter.key,
      title: origin.title,
      triggerTitle: origin.triggerTitle,
      allExecuted: origin.allExecuted,
      sync: origin.sync,
      initAt: origin.initAt,
      ...values
    } : values;
    const instance = await repository.create({
      values: {
        title: `${origin.title} copy`,
        description: origin.description,
        ...revisionData,
        type: origin.type,
        config: typeof trigger2.duplicateConfig === "function" ? await trigger2.duplicateConfig(origin, { transaction }) : origin.config
      },
      transaction
    });
    const originalNodesMap = /* @__PURE__ */ new Map();
    origin.nodes.forEach((node) => {
      originalNodesMap.set(node.id, node);
    });
    const oldToNew = /* @__PURE__ */ new Map();
    const newToOld = /* @__PURE__ */ new Map();
    for await (const node of origin.nodes) {
      const instruction = plugin.instructions.get(node.type);
      const newNode = await instance.createNode(
        {
          type: node.type,
          key: node.key,
          config: typeof instruction.duplicateConfig === "function" ? await instruction.duplicateConfig(node, { transaction }) : node.config,
          title: node.title,
          branchIndex: node.branchIndex
        },
        { transaction }
      );
      oldToNew.set(node.id, newNode);
      newToOld.set(newNode.id, node);
    }
    for await (const [oldId, newNode] of oldToNew.entries()) {
      const oldNode = originalNodesMap.get(oldId);
      const newUpstream = oldNode.upstreamId ? oldToNew.get(oldNode.upstreamId) : null;
      const newDownstream = oldNode.downstreamId ? oldToNew.get(oldNode.downstreamId) : null;
      await newNode.update(
        {
          upstreamId: (newUpstream == null ? void 0 : newUpstream.id) ?? null,
          downstreamId: (newDownstream == null ? void 0 : newDownstream.id) ?? null
        },
        { transaction }
      );
    }
    return instance;
  });
  await next();
}
async function retry(context, next) {
  const plugin = context.app.getPlugin(import_Plugin.default);
  const repository = import_actions.utils.getRepositoryFromParams(context);
  const { filterByTk, filter = {}, values = {} } = context.action.params;
  const ExecutionRepo = context.db.getRepository("executions");
  if (!context.state) {
    context.state = {};
  }
  if (!context.state.messages) {
    context.state.messages = [];
  }
  const workflow = await repository.findOne({
    filterByTk,
    filter,
    appends: ["nodes"],
    context
  });
  const execution = await ExecutionRepo.findOne({
    filter: { key: workflow.key },
    sort: ["-createdAt"]
  });
  if (!execution) {
    context.state.messages.push({ message: "No execution records found for this workflow." });
  }
  const executionId = execution.id;
  const result = await plugin.trigger(workflow, execution.context, { httpContext: context });
  context.app.logger.info(result);
  context.state.messages.push({ message: "Execute successfully" });
  context.body = { executionId };
  await next();
}
async function sync(context, next) {
  const plugin = context.app.getPlugin(import_Plugin.default);
  const repository = import_actions.utils.getRepositoryFromParams(context);
  const { filterByTk, filter = {} } = context.action.params;
  const workflows = await repository.find({
    filterByTk,
    filter
  });
  workflows.forEach((workflow) => {
    plugin.toggle(workflow, false);
    plugin.toggle(workflow);
  });
  context.status = 204;
  await next();
}
async function trigger(ctx, next) {
  var _a, _b;
  if (!ctx.action.params.triggerWorkflows) {
    const plugin = ctx.app.getPlugin(import_Plugin.default);
    const workflow = await ctx.db.getRepository("workflows").findById(ctx.action.params.filterByTk);
    const updateData = JSON.parse(decodeURIComponent(((_a = ctx.action.params) == null ? void 0 : _a.updateData) || ""));
    plugin.trigger(
      workflow,
      {
        data: {
          updateData,
          httpContext: ctx,
          user: (_b = ctx == null ? void 0 : ctx.auth) == null ? void 0 : _b.user
        }
      },
      { httpContext: ctx }
    );
  } else {
    await next();
  }
}
async function moveWorkflow(ctx, next) {
  const { id, targetKey } = ctx.action.params;
  if (!id || !targetKey) {
    ctx.throw(400, "params error");
  }
  const workflowRepo = ctx.db.getRepository("workflows");
  const targetWorkflow = await workflowRepo.findOne({
    filter: {
      key: targetKey,
      enabled: true
    }
  });
  if (!targetWorkflow) {
    ctx.throw(400, "target workflow not found");
  }
  const sourceWorkflow = await workflowRepo.findOne({
    filter: {
      id
    }
  });
  if (!sourceWorkflow) {
    ctx.throw(400, "source workflow not found");
  }
  if (sourceWorkflow.key === targetKey) {
    ctx.throw(400, "same workflow");
  }
  if (sourceWorkflow.current) {
    ctx.throw(400, "cannot move current workflow");
  }
  if (sourceWorkflow.type !== targetWorkflow.type) {
    ctx.throw(400, "the type is different");
  }
  const { allExecuted } = targetWorkflow;
  const transaction = await ctx.db.sequelize.transaction();
  await workflowRepo.update({
    values: { key: targetKey, current: null, allExecuted },
    filter: { id },
    hooks: false,
    // 不触发钩子
    transaction
  });
  const executionRepo = ctx.db.getRepository("executions");
  await executionRepo.update({
    values: { key: targetKey },
    filter: { workflow: { id } },
    silent: true,
    // 不修改updatedAt等数据
    hooks: false,
    // 不触发钩子
    transaction
  });
  const repo = ctx.db.getRepository("approvals");
  if (repo) {
    await repo.update({
      values: { workflowKey: targetKey },
      filter: { workflowId: id },
      hooks: false,
      // 不触发钩子
      transaction
    });
  }
  await transaction.commit();
  ctx.body = {};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  destroy,
  dump,
  load,
  moveWorkflow,
  retry,
  revision,
  sync,
  test,
  trigger,
  update
});
