import { createHash } from "node:crypto";
import { WorkflowDefinition } from "../data/entities.js";
import { getCodeWorkflow } from "./code-registry.js";
function codeWorkflowUuid(workflowId) {
  const hash = createHash("sha256").update(`code-workflow:${workflowId}`).digest("hex");
  return [
    hash.slice(0, 8),
    hash.slice(8, 12),
    `4${hash.slice(13, 16)}`,
    `${(parseInt(hash[16], 16) & 3 | 8).toString(16)}${hash.slice(17, 20)}`,
    hash.slice(20, 32)
  ].join("-");
}
async function findWorkflowDefinition(em, options) {
  const { workflowId, version, tenantId, organizationId } = options;
  const where = {
    workflowId,
    tenantId,
    organizationId,
    deletedAt: null
  };
  if (version !== void 0) {
    where.version = version;
  }
  if (version === void 0) {
    where.enabled = true;
    const dbDef = await em.findOne(WorkflowDefinition, where, {
      orderBy: { version: "DESC" }
    });
    if (dbDef) return dbDef;
  } else {
    const dbDef = await em.findOne(WorkflowDefinition, where);
    if (dbDef) return dbDef;
  }
  const codeDef = getCodeWorkflow(workflowId);
  if (!codeDef) return null;
  if (version === void 0 && !codeDef.enabled) return null;
  return buildVirtualCodeDefinition(codeDef, tenantId, organizationId);
}
function buildVirtualCodeDefinition(codeDef, tenantId, organizationId) {
  const virtual = new WorkflowDefinition();
  virtual.id = codeWorkflowUuid(codeDef.workflowId);
  virtual.workflowId = codeDef.workflowId;
  virtual.workflowName = codeDef.workflowName;
  virtual.description = codeDef.description ?? null;
  virtual.version = codeDef.version;
  virtual.definition = codeDef.definition;
  virtual.metadata = codeDef.metadata ?? null;
  virtual.enabled = codeDef.enabled;
  virtual.codeWorkflowId = codeDef.workflowId;
  virtual.tenantId = tenantId;
  virtual.organizationId = organizationId;
  virtual.createdAt = /* @__PURE__ */ new Date(0);
  virtual.updatedAt = /* @__PURE__ */ new Date(0);
  return virtual;
}
function resolveCodeDefinitionForInstance(instance) {
  const codeDef = getCodeWorkflow(instance.workflowId);
  if (!codeDef) return null;
  if (codeWorkflowUuid(instance.workflowId) !== instance.definitionId) return null;
  return buildVirtualCodeDefinition(codeDef, instance.tenantId, instance.organizationId);
}
async function findDefinitionForInstance(em, instance) {
  const dbDef = await em.findOne(WorkflowDefinition, { id: instance.definitionId });
  if (dbDef) return dbDef;
  return resolveCodeDefinitionForInstance(instance);
}
export {
  codeWorkflowUuid,
  findDefinitionForInstance,
  findWorkflowDefinition,
  resolveCodeDefinitionForInstance
};
//# sourceMappingURL=find-definition.js.map
