const N = {
  triggerToCategory: {},
  schedulerEventTypes: [],
  conditionPathPrefix: "",
  defaultWorkflowCategory: "",
  endEventIds: {
    success: "endEventSuccess",
    failure: "endEventFailure",
    rejected: "endEventRejected"
  },
  endEventNames: {
    success: "Success",
    failure: "Failure",
    rejected: "Rejected"
  },
  startEventId: "startEvent"
}, L = /* @__PURE__ */ new Set([
  "start",
  "end",
  "triggerFixed",
  "addTrigger",
  "addStep"
]), B = (e) => !!e && !L.has(String(e.kind ?? ""));
function b(e, t) {
  return e == null ? "" : String(e).replace(
    /\$\{(\w+)\}/g,
    (o, r) => Object.prototype.hasOwnProperty.call(t, r) ? String(t[r]) : o
  );
}
function V(e, t) {
  var s, E, a, u, m;
  if (!e || typeof e != "object") return "";
  const { from: o, key: r, value: i } = e;
  return o === "literal" ? i === void 0 ? "" : String(i) : o === "task" ? String(((s = t.task) == null ? void 0 : s[r ?? ""]) ?? "") : o === "ctx" ? String(((E = t.ctx) == null ? void 0 : E[r ?? ""]) ?? "") : o === "slot" ? String(((a = t.slot) == null ? void 0 : a[r ?? ""]) ?? "") : o === "formData" ? String(((m = (u = t.slot) == null ? void 0 : u.formData) == null ? void 0 : m[r ?? ""]) ?? "") : "";
}
function J(e, t) {
  var r, i, s;
  const o = e == null ? void 0 : e.source;
  if (!o) return "";
  if (o.type === "literal")
    return typeof o.value == "string" ? o.value : JSON.stringify(o.value ?? "");
  if (o.type === "json" || o.type === "taskConfig") {
    const E = o.shape || {}, a = {};
    return Object.keys(E).forEach((u) => {
      a[u] = V(E[u], t);
    }), JSON.stringify(a);
  }
  if (o.type === "formData") {
    if (o.passthrough) {
      const E = new Set(o.exclude || []), a = {}, u = ((r = t.slot) == null ? void 0 : r.formData) ?? {};
      return Object.keys(u).forEach((m) => {
        E.has(m) || (a[m] = u[m]);
      }), JSON.stringify(a);
    }
    return String(((s = (i = t.slot) == null ? void 0 : i.formData) == null ? void 0 : s[o.key ?? ""]) ?? "");
  }
  return "";
}
function K(e, t) {
  if (!(!e || typeof e != "object" || !t))
    return t.split(".").reduce((o, r) => {
      if (!(o == null || typeof o != "object"))
        return o[r];
    }, e);
}
function W(e, t, o) {
  var I;
  const r = e.operatorMap || {}, i = e.valuesField || "groups", s = (n) => {
    const p = r[String((n == null ? void 0 : n.operator) ?? "")] ?? "==", d = `${o}.${(n == null ? void 0 : n.key) ?? (n == null ? void 0 : n.field) ?? ""}`, f = `'${String((n == null ? void 0 : n.value) ?? "")}'`;
    return p.startsWith(".") ? `${d}${p}(${f})` : p.startsWith("!.") ? `!${d}${p.slice(1)}(${f})` : `${d} ${p} ${f}`;
  }, E = (n) => {
    var g, l;
    const p = Array.isArray(n) ? n : [];
    if (p.length === 0) return null;
    const d = p.map(s), y = ((g = p[0]) == null ? void 0 : g.connector) === "or" || ((l = p[0]) == null ? void 0 : l.logicalOperator) === "OR" ? "||" : "&&";
    return d.join(` ${y} `);
  }, a = [];
  let u = 1;
  const m = (n, p) => {
    a.push({
      id: `rule${u}`,
      inputEntries: [
        {
          id: `rule${u}InputEntry1`,
          text: n ? `\${(${n})}` : ""
        }
      ],
      outputEntries: [
        {
          id: `rule${u}OutputEntry1`,
          text: `"${p}"`
        }
      ]
    }), u += 1;
  }, v = Array.isArray((I = t == null ? void 0 : t.formData) == null ? void 0 : I.groupBlocks) ? t.formData.groupBlocks : [];
  if (v.length > 0)
    return v.forEach((n) => {
      const p = Array.isArray(n == null ? void 0 : n[i]) ? n[i] : [], d = E(n == null ? void 0 : n.conditions);
      p.forEach((f) => m(d, f));
    }), a;
  const h = (t == null ? void 0 : t.formData) ?? {}, $ = h._conditionConfig ?? h.conditionConfig;
  return $ && typeof $ == "object" && Object.keys($).forEach((n) => {
    const p = $[n], d = E(p), f = Object.prototype.hasOwnProperty.call(h, n) ? h[n] : K(h, n);
    Array.isArray(f) ? f.forEach((y) => {
      const g = typeof y == "object" && y !== null ? y.value ?? y.label ?? y : y;
      m(d, g);
    }) : f != null && f !== "" ? m(d, f) : d && m(d, "");
  }), a;
}
function k(e, t, o) {
  return {
    mappings: [],
    name: e.tableName,
    decision: {
      id: e.tableName,
      name: e.tableName,
      decisionTable: {
        id: `decisionTable_${e.tableName}`,
        hitPolicy: e.hitPolicy || "FIRST",
        inputs: [
          {
            id: `input_${e.tableName}`,
            inputExpression: {
              id: `inputExpr_${e.tableName}`,
              typeRef: "string",
              text: e.inputExpr
            }
          }
        ],
        outputs: (e.outputs || []).map((r) => ({
          id: r.id,
          label: r.label,
          typeRef: r.typeRef || "string",
          name: r.name
        })),
        rules: W(e, t, o)
      }
    }
  };
}
function G(e, t, o, r) {
  var f, y, g;
  const i = (f = t == null ? void 0 : t.ui) == null ? void 0 : f.bpmnEmit;
  if (!i)
    return {
      serviceTasks: [
        {
          id: e.id,
          name: (t == null ? void 0 : t.name) || e.descriptorType,
          configuration: Array.isArray(t == null ? void 0 : t.configuration) ? t.configuration : [],
          input: e.formData || {}
        }
      ],
      gateways: [],
      callActivities: [],
      templateFlows: [],
      dmn: null,
      bpmnEntry: e.id,
      bpmnExit: e.id,
      outgoingConditions: {},
      endsNeeded: /* @__PURE__ */ new Set()
    };
  const s = {
    id: e.id,
    endFailure: r.endEventIds.failure,
    endRejected: r.endEventIds.rejected,
    endSuccess: r.endEventIds.success
  }, E = { task: t, slot: e, ctx: o }, a = (i.serviceTasks || []).map((l) => ({
    id: b(l.idTemplate, s),
    name: l.name,
    flowableClass: l.flowableClass,
    extensionElements: {
      fields: (l.extensionFields || []).map((w) => ({
        name: w.name,
        stringValue: J(w, E)
      }))
    }
  }));
  let u = null;
  const m = [];
  i.gateway && (u = b(i.gateway.idTemplate, s), s.gateway = u, m.push({ id: u, name: i.gateway.name }));
  const v = /* @__PURE__ */ new Set(), h = (i.templateFlows || []).map((l) => {
    const w = b(l.from, s), T = b(l.to, s);
    return T === r.endEventIds.failure && v.add(r.endEventIds.failure), T === r.endEventIds.rejected && v.add(r.endEventIds.rejected), {
      id: l.idTemplate ? b(l.idTemplate, s) : `${w}-to-${T}`,
      sourceRef: w,
      targetRef: T,
      conditionExpression: l.condition ? b(l.condition, s) : null
    };
  }), $ = [], I = i.dmnEmit ? k(i.dmnEmit, e, r.conditionPathPrefix) : null, n = ((y = a[0]) == null ? void 0 : y.id) ?? e.id, p = u ?? ((g = a[a.length - 1]) == null ? void 0 : g.id) ?? e.id, d = {};
  return Object.keys(i.outgoingConditions || {}).forEach((l) => {
    d[l] = b(
      i.outgoingConditions[l],
      s
    );
  }), {
    serviceTasks: a,
    gateways: m,
    callActivities: $,
    templateFlows: h,
    dmn: I,
    bpmnEntry: n,
    bpmnExit: p,
    outgoingConditions: d,
    endsNeeded: v
  };
}
function U(e) {
  var R, A, D, S;
  const { state: t, tasksByKey: o, context: r, config: i } = e, s = {
    ...N,
    ...i ?? {},
    triggerToCategory: { ...N.triggerToCategory, ...(i == null ? void 0 : i.triggerToCategory) ?? {} },
    schedulerEventTypes: (i == null ? void 0 : i.schedulerEventTypes) ?? N.schedulerEventTypes,
    endEventIds: { ...N.endEventIds, ...(i == null ? void 0 : i.endEventIds) ?? {} },
    endEventNames: { ...N.endEventNames, ...(i == null ? void 0 : i.endEventNames) ?? {} }
  }, E = Array.isArray(t == null ? void 0 : t.slots) ? t.slots : [], a = E.find((c) => c.kind === "triggerFixed"), u = (R = a == null ? void 0 : a.nodeData) == null ? void 0 : R.eventType, m = ((A = a == null ? void 0 : a.nodeData) == null ? void 0 : A.type) || "event", v = (D = a == null ? void 0 : a.nodeData) == null ? void 0 : D.sources, h = Array.isArray(v) ? v.map(
    (c) => typeof c == "string" ? c : (c == null ? void 0 : c.value) ?? (c == null ? void 0 : c.key) ?? ""
  ).filter(Boolean) : [], $ = s.triggerToCategory[u ?? ""] ?? s.defaultWorkflowCategory, n = !!u && s.schedulerEventTypes.includes(u) ? ["SCHEDULER"] : h, d = E.filter(B).map((c) => ({
    slot: c,
    emit: G(c, o[c.descriptorType ?? ""] ?? {}, r, s)
  })), f = [], y = [], g = [], l = [], w = [], T = /* @__PURE__ */ new Set();
  d.forEach(({ emit: c }) => {
    f.push(...c.serviceTasks), y.push(...c.gateways), g.push(...c.callActivities), l.push(...c.templateFlows), c.dmn && w.push(c.dmn), c.endsNeeded.forEach((C) => T.add(C));
  });
  const x = [];
  if (d.length > 0) {
    x.push({
      id: `${s.startEventId}-to-${d[0].emit.bpmnEntry}`,
      sourceRef: s.startEventId,
      targetRef: d[0].emit.bpmnEntry,
      conditionExpression: null
    });
    for (let C = 0; C < d.length - 1; C += 1) {
      const j = d[C].emit, F = d[C + 1].emit, P = j.outgoingConditions.success ?? j.outgoingConditions.pass ?? j.outgoingConditions.approved ?? null;
      x.push({
        id: `${j.bpmnExit}-to-${F.bpmnEntry}`,
        sourceRef: j.bpmnExit,
        targetRef: F.bpmnEntry,
        conditionExpression: P
      });
    }
    const c = d[d.length - 1].emit;
    x.push({
      id: `${c.bpmnExit}-to-${s.endEventIds.success}`,
      sourceRef: c.bpmnExit,
      targetRef: s.endEventIds.success,
      conditionExpression: null
    });
  } else
    x.push({
      id: `${s.startEventId}-to-${s.endEventIds.success}`,
      sourceRef: s.startEventId,
      targetRef: s.endEventIds.success,
      conditionExpression: null
    });
  const _ = [
    {
      id: s.endEventIds.success,
      name: s.endEventNames.success,
      executionListener: null
    },
    ...T.has(s.endEventIds.failure) ? [{ id: s.endEventIds.failure, name: s.endEventNames.failure }] : [],
    ...T.has(s.endEventIds.rejected) ? [{ id: s.endEventIds.rejected, name: s.endEventNames.rejected }] : []
  ], O = {
    id: s.startEventId,
    name: "Start",
    ...m === "event" ? {
      messageEventDefinition: {
        messageRef: `msg_${(u || "EVENT").toLowerCase()}_${n.length > 0 ? n.join("_").toLowerCase() : "default"}_${r.customerKey}`
      }
    } : {}
  };
  return {
    canvasState: {
      slots: E,
      branches: (t == null ? void 0 : t.branches) ?? {}
    },
    bpmn: {
      customerId: `${r.customerKey}`,
      workflowCategory: $,
      sources: n,
      process: {
        name: r.workflowName,
        isExecutable: "true"
      },
      startEvent: O,
      endEvent: _,
      sequenceFlows: [...x, ...l],
      exclusiveGateways: y,
      serviceTasks: f,
      callActivities: g
    },
    ...m === "event" ? {
      message: {
        id: `msg_${(u || "event").toLowerCase()}_${n.length > 0 ? n.join("_").toLowerCase() : "default"}_${r.customerKey}`,
        name: `msg_${(u || "event").toLowerCase()}_${n.length > 0 ? n.join("_").toLowerCase() : "default"}_${r.customerKey}`
      },
      dmns: w
    } : {
      eventConfig: [
        {
          eventType: u,
          config: {
            type: u,
            ...((S = a == null ? void 0 : a.nodeData) == null ? void 0 : S.scheduler) ?? {}
          }
        }
      ]
    }
  };
}
export {
  U as b
};
//# sourceMappingURL=buildBackendPayload-4SwOp7St.js.map
