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,
  listExtended: () => listExtended,
  load: () => load,
  moveWorkflow: () => moveWorkflow,
  retry: () => retry,
  revision: () => revision,
  sync: () => sync,
  test: () => test,
  trigger: () => trigger,
  update: () => update
});
module.exports = __toCommonJS(workflows_exports);
var import_server = require("@tego/server");
var import_Plugin = __toESM(require("../Plugin"));
var import_utils = require("../utils");
var import_workflows = require("./workflows.helpers");
async function listExtended(ctx, next) {
  var _a;
  await import_server.actions.list(ctx, next);
  if (((_a = ctx.body) == null ? void 0 : _a.rows) && Array.isArray(ctx.body.rows) && ctx.body.rows.length > 0) {
    const workflows = ctx.body.rows;
    for (let index = 0; index < workflows.length; index++) {
      const workflow = workflows[index];
      const row = ctx.body.rows[index];
      if (!row) continue;
      const workflowData = (0, import_workflows.getWorkflowData)(workflow);
      const executedTime = await (0, import_workflows.getLatestExecutedTimeForWorkflow)(ctx, workflowData == null ? void 0 : workflowData.id, workflowData == null ? void 0 : workflowData.key);
      (0, import_workflows.setLatestExecutedTime)(row, executedTime);
      const eventSourceName = await (0, import_workflows.getEventSourceNameForWorkflow)(ctx, workflowData == null ? void 0 : workflowData.key);
      (0, import_workflows.setEventSourceName)(row, eventSourceName);
      const categories = await (0, import_workflows.getCategoriesForWorkflow)(ctx, workflow, workflowData == null ? void 0 : workflowData.key);
      (0, import_workflows.setCategories)(row, categories);
    }
  }
  return ctx;
}
async function update(ctx, next) {
  const repository = import_server.utils.getRepositoryFromParams(ctx);
  const { filterByTk, values } = ctx.action.params;
  ctx.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 ctx.throw(400, "config of executed workflow can not be updated");
    }
  }
  return import_server.actions.update(ctx, next);
}
async function destroy(ctx, next) {
  const repository = import_server.utils.getRepositoryFromParams(ctx);
  const { filterByTk, filter } = ctx.action.params;
  await ctx.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_server.Op.not]: true }
      },
      fields: ["id"],
      transaction
    });
    revisions.forEach((item) => ids.add(item.id));
    ctx.body = await repository.destroy({
      filterByTk: Array.from(ids),
      individualHooks: true,
      transaction
    });
  });
  next();
}
async function dump(ctx, next) {
  const repository = import_server.utils.getRepositoryFromParams(ctx);
  const { filterByTk, filter = {}, values = {} } = ctx.action.params;
  ctx.body = await ctx.db.sequelize.transaction(async (transaction) => {
    const origin = await repository.findOne({
      filterByTk,
      filter,
      appends: ["nodes"],
      context: ctx,
      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(ctx, next) {
  const plugin = ctx.tego.pm.get(import_Plugin.default);
  const repository = import_server.utils.getRepositoryFromParams(ctx);
  const { values = {} } = ctx.action.params;
  ctx.body = await ctx.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(ctx, next) {
  var _a;
  const plugin = ctx.tego.pm.get(import_Plugin.default);
  const repository = import_server.utils.getRepositoryFromParams(ctx);
  const { filterByTk, filter = {}, values = {} } = ctx.action.params;
  if (!ctx.state) {
    ctx.state = {};
  }
  if (!ctx.state.messages) {
    ctx.state.messages = [];
  }
  const workflow = await repository.findOne({
    filterByTk,
    filter,
    appends: ["nodes"],
    context: ctx
  });
  if (!workflow) {
    return ctx.throw(404, "Workflow not found");
  }
  const execution = await (0, import_utils.triggerWorkflowAndGetExecution)(
    plugin,
    workflow,
    {
      data: values.data || {},
      user: ((_a = ctx == null ? void 0 : ctx.state) == null ? void 0 : _a.currentUser) || {}
    },
    { httpContext: ctx, transaction: ctx.transaction },
    ctx.db
  );
  if (!execution) {
    ctx.state.messages.push({
      message: ctx.t("Failed to create execution", { ns: "workflow" })
    });
    return ctx.throw(500, "Failed to create execution");
  }
  ctx.state.messages.push({
    message: ctx.t("Test execution ended", { ns: "workflow" })
  });
  ctx.body = execution;
  await next();
}
async function revision(ctx, next) {
  const plugin = ctx.tego.pm.get(import_Plugin.default);
  const repository = import_server.utils.getRepositoryFromParams(ctx);
  const { filterByTk, filter = {}, values = {} } = ctx.action.params;
  ctx.body = await ctx.db.sequelize.transaction(async (transaction) => {
    const origin = await repository.findOne({
      filterByTk,
      filter,
      appends: ["nodes"],
      context: ctx,
      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(ctx, next) {
  const plugin = ctx.tego.pm.get(import_Plugin.default);
  const repository = import_server.utils.getRepositoryFromParams(ctx);
  const { filterByTk, filter = {}, values = {} } = ctx.action.params;
  const ExecutionRepo = ctx.db.getRepository("executions");
  if (!ctx.state) {
    ctx.state = {};
  }
  if (!ctx.state.messages) {
    ctx.state.messages = [];
  }
  const workflow = await repository.findOne({
    filterByTk,
    filter,
    appends: ["nodes"],
    context: ctx
  });
  const execution = await ExecutionRepo.findOne({
    filter: { key: workflow.key },
    sort: ["-createdAt"]
  });
  if (!execution) {
    ctx.state.messages.push({
      message: ctx.t("No execution records found for this workflow.", { ns: "workflow" })
    });
  }
  try {
    const newExecution = await (0, import_utils.triggerWorkflowAndGetExecution)(
      plugin,
      workflow,
      execution.context,
      { httpContext: ctx, transaction: ctx.transaction },
      ctx.db
    );
    if (!newExecution) {
      ctx.state.messages.push({
        message: ctx.t("Failed to create execution", { ns: "workflow" })
      });
      ctx.body = {
        error: ctx.t("Failed to create execution", { ns: "workflow" })
      };
      return await next();
    }
    ctx.state.messages.push({ message: ctx.t("Execute ended", { ns: "workflow" }) });
    ctx.body = newExecution;
  } catch (error) {
    ctx.tego.logger.error(`Failed to retry execution ${execution.id}: ${error.message}`);
    ctx.state.messages.push({
      message: ctx.t("Failed to retry execution", { ns: "workflow" }),
      error: error.message
    });
    ctx.body = {
      error: error.message
    };
  }
  await next();
}
async function sync(ctx, next) {
  const plugin = ctx.tego.pm.get(import_Plugin.default);
  const repository = import_server.utils.getRepositoryFromParams(ctx);
  const { filterByTk, filter = {} } = ctx.action.params;
  const workflows = await repository.find({
    filterByTk,
    filter
  });
  workflows.forEach((workflow) => {
    plugin.toggle(workflow, false);
    plugin.toggle(workflow);
  });
  ctx.status = 204;
  await next();
}
async function trigger(ctx, next) {
  var _a, _b;
  if (!ctx.action.params.triggerWorkflows) {
    const plugin = ctx.tego.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,
  listExtended,
  load,
  moveWorkflow,
  retry,
  revision,
  sync,
  test,
  trigger,
  update
});
