/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

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 MultiConditionsInstruction_exports = {};
__export(MultiConditionsInstruction_exports, {
  MultiConditionsInstruction: () => MultiConditionsInstruction,
  default: () => MultiConditionsInstruction_default
});
module.exports = __toCommonJS(MultiConditionsInstruction_exports);
var import_joi = __toESM(require("joi"));
var import_evaluators = require("@nocobase/evaluators");
var import__ = require(".");
var import_constants = require("../constants");
var import_logicCalculate = require("../logicCalculate");
class MultiConditionsInstruction extends import__.Instruction {
  configSchema = import_joi.default.object({
    conditions: import_joi.default.array().items(
      import_joi.default.object({
        uid: import_joi.default.string(),
        title: import_joi.default.string(),
        engine: import_joi.default.string(),
        calculation: import_joi.default.any(),
        expression: import_joi.default.string()
      })
    ),
    continueOnNoMatch: import_joi.default.boolean()
  });
  async run(node, prevJob, processor) {
    const { conditions = [], continueOnNoMatch = false } = node.config || {};
    const meta = { conditions: [] };
    const job = processor.saveJob({
      status: import_constants.JOB_STATUS.PENDING,
      result: null,
      meta,
      nodeId: node.id,
      nodeKey: node.key,
      upstreamId: (prevJob == null ? void 0 : prevJob.id) ?? null
    });
    for (let cursor = 0; cursor < conditions.length; cursor++) {
      const branchIndex = cursor + 1;
      const condition = conditions[cursor];
      let conditionResult;
      try {
        conditionResult = this.evaluateCondition(condition, node, processor);
      } catch (error) {
        conditionResult = error instanceof Error ? error.message : String(error);
        processor.logger.error(`[multi-conditions] evaluate condition[${cursor}] error:`, { error });
      } finally {
        meta.conditions.push(conditionResult);
        job.set("result", conditionResult);
      }
      if (typeof conditionResult === "string") {
        job.set("status", import_constants.JOB_STATUS.ERROR);
        return job;
      }
      if (conditionResult === true) {
        const branchNode = this.getBranchNode(node, processor, branchIndex);
        job.set("status", import_constants.JOB_STATUS.RESOLVED);
        if (branchNode) {
          await processor.run(branchNode, job);
          return;
        }
        return job;
      }
    }
    job.set("status", continueOnNoMatch ? import_constants.JOB_STATUS.RESOLVED : import_constants.JOB_STATUS.FAILED);
    const defaultBranch = this.getBranchNode(node, processor, 0);
    if (defaultBranch) {
      await processor.run(defaultBranch, job);
      return;
    }
    return job;
  }
  async resume(node, branchJob, processor) {
    const job = processor.findBranchParentJob(branchJob, node);
    if (!job) {
      throw new Error("Parent job not found");
    }
    const { continueOnNoMatch = false } = node.config || {};
    const jobNode = processor.nodesMap.get(branchJob.nodeId);
    const branchStartNode = processor.findBranchStartNode(jobNode, node);
    const branchIndex = branchStartNode.branchIndex;
    if (branchJob.status === import_constants.JOB_STATUS.RESOLVED) {
      if (branchIndex > 0) {
        job.set({
          status: import_constants.JOB_STATUS.RESOLVED
        });
        return job;
      }
      job.set({ status: continueOnNoMatch ? import_constants.JOB_STATUS.RESOLVED : import_constants.JOB_STATUS.FAILED });
      return job;
    }
    return processor.exit(branchJob.status);
  }
  evaluateCondition(condition, node, processor) {
    const { engine = "basic", calculation, expression } = condition ?? {};
    const evaluator = import_evaluators.evaluators.get(engine);
    return evaluator ? evaluator(expression, processor.getScope(node.id)) : (0, import_logicCalculate.logicCalculate)(processor.getParsedValue(calculation, node.id));
  }
  getBranchNode(node, processor, branchIndex) {
    return processor.getBranches(node).find((item) => Number(item.branchIndex) === Number(branchIndex));
  }
}
var MultiConditionsInstruction_default = MultiConditionsInstruction;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  MultiConditionsInstruction
});
