import { z } from "zod";
import { parseDuration } from "../lib/duration.js";
const uuid = z.uuid();
const containsTemplate = (value) => value.includes("{{");
function isValidDurationString(value) {
  if (typeof value !== "string" || value.length === 0) return false;
  if (containsTemplate(value)) return true;
  try {
    const ms = parseDuration(value);
    return Number.isFinite(ms) && ms > 0;
  } catch {
    return false;
  }
}
function isValidIsoDateString(value) {
  if (typeof value !== "string" || value.length === 0) return false;
  if (containsTemplate(value)) return true;
  const d = new Date(value);
  return !Number.isNaN(d.getTime());
}
function isFutureIsoDateString(value) {
  if (typeof value !== "string" || value.length === 0) return false;
  if (containsTemplate(value)) return true;
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return false;
  return d.getTime() > Date.now();
}
const DURATION_ERROR = "Invalid duration. Use ISO 8601 (e.g., PT5M, PT1H, P1D) or simple format (5m, 1h, 3d)";
const UNTIL_ERROR = 'Invalid "until". Provide an ISO 8601 datetime string';
const UNTIL_PAST_ERROR = '"until" must be a future datetime';
const workflowStepTypeSchema = z.enum([
  "START",
  "END",
  "USER_TASK",
  "AUTOMATED",
  "PARALLEL_FORK",
  "PARALLEL_JOIN",
  "SUB_WORKFLOW",
  "WAIT_FOR_SIGNAL",
  "WAIT_FOR_TIMER"
]);
const workflowInstanceStatusSchema = z.enum([
  "RUNNING",
  "PAUSED",
  "COMPLETED",
  "FAILED",
  "CANCELLED",
  "COMPENSATING",
  "COMPENSATED",
  "WAITING_FOR_ACTIVITIES",
  "FORKED"
]);
const workflowBranchInstanceStatusSchema = z.enum([
  "ACTIVE",
  "PAUSED",
  "WAITING_FOR_ACTIVITIES",
  "COMPLETED",
  "FAILED",
  "CANCELLED"
]);
const stepInstanceStatusSchema = z.enum([
  "PENDING",
  "ACTIVE",
  "COMPLETED",
  "FAILED",
  "SKIPPED",
  "CANCELLED"
]);
const userTaskStatusSchema = z.enum([
  "PENDING",
  "IN_PROGRESS",
  "COMPLETED",
  "CANCELLED",
  "ESCALATED"
]);
const transitionTriggerSchema = z.enum(["auto", "manual", "signal", "timer"]);
const activityTypeSchema = z.enum([
  "SEND_EMAIL",
  "CALL_API",
  "UPDATE_ENTITY",
  "EMIT_EVENT",
  "CALL_WEBHOOK",
  "EXECUTE_FUNCTION",
  "WAIT"
]);
const escalationTriggerSchema = z.enum(["sla_breach", "no_progress", "custom"]);
const escalationActionSchema = z.enum(["reassign", "notify", "escalate"]);
const userTaskConfigSchema = z.object({
  // Support both custom fields array format and JSON Schema format
  formSchema: z.union([
    // Custom format with fields array
    z.object({
      fields: z.array(z.object({
        name: z.string().min(1),
        type: z.string().min(1),
        label: z.string().min(1),
        required: z.boolean().optional(),
        options: z.array(z.any()).optional()
      }))
    }),
    // JSON Schema format with properties
    z.object({
      type: z.literal("object").optional(),
      properties: z.record(z.string(), z.any()),
      required: z.array(z.string()).optional()
    })
  ]).optional(),
  assignedTo: z.union([
    z.string(),
    z.array(z.string())
  ]).optional(),
  assignmentRule: z.string().optional(),
  // Business rule ID
  slaDuration: z.string().optional(),
  // ISO 8601 duration
  escalationRules: z.array(z.object({
    trigger: escalationTriggerSchema,
    action: escalationActionSchema,
    escalateTo: z.string().optional(),
    notifyUsers: z.array(z.string()).optional()
  })).optional()
});
const subWorkflowConfigSchema = z.object({
  subWorkflowId: z.string().min(1, "Sub-workflow ID is required"),
  version: z.number().int().positive().optional(),
  inputMapping: z.record(z.string(), z.string()).optional(),
  outputMapping: z.record(z.string(), z.string()).optional(),
  timeoutMs: z.number().int().positive().optional()
});
const callApiConfigSchema = z.object({
  endpoint: z.string().min(1, "API endpoint is required"),
  method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]).default("GET"),
  headers: z.record(z.string(), z.string()).optional(),
  body: z.any().optional(),
  validateTenantMatch: z.boolean().default(true).optional(),
  timeout: z.number().int().positive().optional()
});
const callWebhookConfigSchema = z.object({
  url: z.string().min(1, "Webhook URL is required"),
  method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).default("POST"),
  headers: z.record(z.string(), z.string()).optional(),
  body: z.any().optional()
});
const retryPolicySchema = z.object({
  maxAttempts: z.number().int().min(1).max(10),
  backoffMs: z.number().int().min(0)
});
const activityRetryPolicySchema = z.object({
  maxAttempts: z.number().int().min(1).max(10),
  initialIntervalMs: z.number().int().min(0),
  backoffCoefficient: z.number().min(1).max(10),
  maxIntervalMs: z.number().int().min(0)
});
const activityDefinitionSchema = z.object({
  activityId: z.string().min(1).max(100).regex(/^[a-z0-9_-]+$/, "Activity ID must contain only lowercase letters, numbers, hyphens, and underscores"),
  activityName: z.string().min(1).max(255),
  activityType: activityTypeSchema,
  config: z.record(z.string(), z.any()),
  async: z.boolean().default(false).optional(),
  // For Phase 8.3
  retryPolicy: activityRetryPolicySchema.optional(),
  timeout: z.string().optional(),
  // ISO 8601 duration
  compensation: z.object({
    activityId: z.string().min(1),
    // ID of compensation activity
    automatic: z.boolean().default(true).optional()
    // Auto-trigger on failure
  }).optional()
  // Compensation configuration (Phase 8.2)
}).superRefine((activity, ctx) => {
  if (activity.activityType !== "WAIT") return;
  const config = activity.config || {};
  const hasDuration = config.duration != null && config.duration !== "";
  const hasUntil = config.until != null && config.until !== "";
  if (!hasDuration && !hasUntil) {
    ctx.addIssue({
      code: "custom",
      path: ["config"],
      message: 'WAIT activity requires "duration" or "until"'
    });
    return;
  }
  if (hasDuration && hasUntil) {
    ctx.addIssue({
      code: "custom",
      path: ["config"],
      message: 'WAIT activity accepts "duration" OR "until", not both'
    });
    return;
  }
  if (hasDuration && !isValidDurationString(config.duration)) {
    ctx.addIssue({
      code: "custom",
      path: ["config", "duration"],
      message: DURATION_ERROR
    });
  }
  if (hasUntil) {
    if (!isValidIsoDateString(config.until)) {
      ctx.addIssue({
        code: "custom",
        path: ["config", "until"],
        message: UNTIL_ERROR
      });
    } else if (!isFutureIsoDateString(config.until)) {
      ctx.addIssue({
        code: "custom",
        path: ["config", "until"],
        message: UNTIL_PAST_ERROR
      });
    }
  }
});
const localizedMessageSchema = z.record(z.string(), z.string());
const startPreConditionSchema = z.object({
  ruleId: z.string().min(1).max(50),
  // Business rule ID
  required: z.boolean().default(true),
  validationMessage: localizedMessageSchema.optional()
  // Optional localized error messages
});
const workflowStepSchema = z.object({
  stepId: z.string().min(1).max(100).regex(/^[a-z0-9_-]+$/, "Step ID must contain only lowercase letters, numbers, hyphens, and underscores"),
  stepName: z.string().min(1).max(255),
  stepType: workflowStepTypeSchema,
  description: z.string().max(1e3).optional(),
  config: z.record(z.string(), z.any()).optional(),
  userTaskConfig: userTaskConfigSchema.optional(),
  subWorkflowConfig: subWorkflowConfigSchema.optional(),
  signalConfig: z.object({
    signalName: z.string().min(1),
    timeout: z.string().optional()
  }).optional(),
  activities: z.array(activityDefinitionSchema).optional(),
  timeout: z.string().optional(),
  // ISO 8601 duration
  retryPolicy: retryPolicySchema.optional(),
  // Pre-conditions for START step (business rules to validate before workflow can be started)
  preConditions: z.array(startPreConditionSchema).optional()
}).superRefine((step, ctx) => {
  if (step.stepType !== "WAIT_FOR_TIMER") return;
  const config = step.config || {};
  const hasDuration = config.duration != null && config.duration !== "";
  const hasUntil = config.until != null && config.until !== "";
  if (!hasDuration && !hasUntil) {
    ctx.addIssue({
      code: "custom",
      path: ["config"],
      message: 'WAIT_FOR_TIMER step requires "duration" or "until"'
    });
    return;
  }
  if (hasDuration && hasUntil) {
    ctx.addIssue({
      code: "custom",
      path: ["config"],
      message: 'WAIT_FOR_TIMER step accepts "duration" OR "until", not both'
    });
    return;
  }
  if (hasDuration && !isValidDurationString(config.duration)) {
    ctx.addIssue({
      code: "custom",
      path: ["config", "duration"],
      message: DURATION_ERROR
    });
  }
  if (hasUntil) {
    if (!isValidIsoDateString(config.until)) {
      ctx.addIssue({
        code: "custom",
        path: ["config", "until"],
        message: UNTIL_ERROR
      });
    } else if (!isFutureIsoDateString(config.until)) {
      ctx.addIssue({
        code: "custom",
        path: ["config", "until"],
        message: UNTIL_PAST_ERROR
      });
    }
  }
});
const transitionConditionSchema = z.object({
  ruleId: z.string().min(1).max(50),
  // Business rule ID
  required: z.boolean().default(true)
});
const workflowTransitionSchema = z.object({
  transitionId: z.string().min(1).max(100).regex(/^[a-z0-9_-]+$/, "Transition ID must contain only lowercase letters, numbers, hyphens, and underscores"),
  fromStepId: z.string().min(1).max(100),
  toStepId: z.string().min(1).max(100),
  transitionName: z.string().max(255).optional(),
  trigger: transitionTriggerSchema,
  preConditions: z.array(transitionConditionSchema).optional(),
  postConditions: z.array(transitionConditionSchema).optional(),
  activities: z.array(activityDefinitionSchema).optional(),
  // Activities to execute during transition
  continueOnActivityFailure: z.boolean().default(false).optional(),
  // If true, transition continues even when activities fail
  priority: z.number().int().min(0).max(9999).default(0)
});
const workflowDefinitionTriggerSchema = z.object({
  triggerId: z.string().min(1).max(100).regex(/^[a-z0-9_-]+$/, "Trigger ID must contain only lowercase letters, numbers, hyphens, and underscores"),
  name: z.string().min(1).max(255),
  description: z.string().max(2e3).optional().nullable(),
  eventPattern: z.string().min(1, "Event pattern is required").max(255, "Event pattern must be at most 255 characters").regex(
    /^(\*|[a-z0-9_]+(\.[a-z0-9_*]+)*)$/i,
    'Event pattern must be "*" or a dot-separated pattern with optional wildcards (e.g., "customers.people.created", "sales.orders.*")'
  ),
  config: z.object({
    filterConditions: z.array(z.object({
      field: z.string().min(1).max(255),
      operator: z.enum(["eq", "neq", "gt", "gte", "lt", "lte", "contains", "startsWith", "endsWith", "in", "notIn", "exists", "notExists", "regex"]),
      value: z.any()
    })).max(20).optional(),
    contextMapping: z.array(z.object({
      targetKey: z.string().min(1).max(100),
      sourceExpression: z.string().min(1).max(255),
      defaultValue: z.any().optional()
    })).max(50).optional(),
    debounceMs: z.number().int().min(0).max(36e5).optional(),
    maxConcurrentInstances: z.number().int().min(1).max(1e3).optional()
  }).optional().nullable(),
  enabled: z.boolean().default(true),
  priority: z.number().int().min(0).max(9999).default(0)
});
function validateParallelForkJoin(definition) {
  const issues = [];
  const steps = definition.steps ?? [];
  const transitions = definition.transitions ?? [];
  const stepById = /* @__PURE__ */ new Map();
  for (const step of steps) stepById.set(step.stepId, step);
  const outgoingByStep = /* @__PURE__ */ new Map();
  const incomingCountByStep = /* @__PURE__ */ new Map();
  for (const transition of transitions) {
    const list = outgoingByStep.get(transition.fromStepId) ?? [];
    list.push(transition);
    outgoingByStep.set(transition.fromStepId, list);
    incomingCountByStep.set(transition.toStepId, (incomingCountByStep.get(transition.toStepId) ?? 0) + 1);
  }
  const forkSteps = steps.filter((step) => step.stepType === "PARALLEL_FORK");
  const joinSteps = steps.filter((step) => step.stepType === "PARALLEL_JOIN");
  const pairedJoinIds = /* @__PURE__ */ new Set();
  for (const fork of forkSteps) {
    const joinStepId = fork.config?.joinStepId ?? void 0;
    if (!joinStepId) {
      issues.push({ code: "MISSING_JOIN_STEP_ID", stepId: fork.stepId, message: `PARALLEL_FORK "${fork.stepId}" must declare config.joinStepId` });
      continue;
    }
    const joinStep = stepById.get(joinStepId);
    if (!joinStep) {
      issues.push({ code: "JOIN_STEP_NOT_FOUND", stepId: fork.stepId, message: `PARALLEL_FORK "${fork.stepId}" references missing join step "${joinStepId}"` });
      continue;
    }
    if (joinStep.stepType !== "PARALLEL_JOIN") {
      issues.push({ code: "JOIN_STEP_WRONG_TYPE", stepId: fork.stepId, message: `Step "${joinStepId}" referenced by fork "${fork.stepId}" is not a PARALLEL_JOIN` });
      continue;
    }
    pairedJoinIds.add(joinStepId);
    const backForkStepId = joinStep.config?.forkStepId ?? void 0;
    if (!backForkStepId) {
      issues.push({ code: "MISSING_FORK_STEP_ID", stepId: joinStepId, message: `PARALLEL_JOIN "${joinStepId}" must declare config.forkStepId` });
    } else if (backForkStepId !== fork.stepId) {
      issues.push({ code: "FORK_JOIN_MISMATCH", stepId: joinStepId, message: `PARALLEL_JOIN "${joinStepId}" back-reference forkStepId "${backForkStepId}" does not match fork "${fork.stepId}"` });
    }
    const autoBranches = (outgoingByStep.get(fork.stepId) ?? []).filter((transition) => transition.trigger === "auto");
    if (autoBranches.length < 2) {
      issues.push({ code: "FORK_TOO_FEW_BRANCHES", stepId: fork.stepId, message: `PARALLEL_FORK "${fork.stepId}" must have at least 2 outgoing auto transitions (found ${autoBranches.length})` });
    }
    const branchKeys = /* @__PURE__ */ new Set();
    for (const branch of autoBranches) {
      if (branchKeys.has(branch.transitionId)) {
        issues.push({ code: "DUPLICATE_BRANCH_KEY", stepId: fork.stepId, message: `PARALLEL_FORK "${fork.stepId}" has duplicate branch key "${branch.transitionId}"` });
      }
      branchKeys.add(branch.transitionId);
    }
    if ((incomingCountByStep.get(joinStepId) ?? 0) < 2) {
      issues.push({ code: "JOIN_TOO_FEW_INCOMING", stepId: joinStepId, message: `PARALLEL_JOIN "${joinStepId}" must have at least 2 incoming transitions` });
    }
    const fullyExplored = /* @__PURE__ */ new Set();
    const onStack = /* @__PURE__ */ new Set();
    let reportedNesting = false;
    let reportedNoConvergence = false;
    let reportedCycle = false;
    const visit = (stepId) => {
      if (stepId === joinStepId) return;
      if (stepId === fork.stepId) {
        if (!reportedCycle) {
          issues.push({ code: "FORK_JOIN_CYCLE", stepId: fork.stepId, message: `A branch of fork "${fork.stepId}" loops back to the fork before reaching join "${joinStepId}"` });
          reportedCycle = true;
        }
        return;
      }
      const step = stepById.get(stepId);
      if (!step) {
        if (!reportedNoConvergence) {
          issues.push({ code: "NO_CONVERGENCE_TO_JOIN", stepId: fork.stepId, message: `A branch of fork "${fork.stepId}" reaches missing step "${stepId}" instead of join "${joinStepId}"` });
          reportedNoConvergence = true;
        }
        return;
      }
      if (step.stepType === "END") {
        if (!reportedNoConvergence) {
          issues.push({ code: "NO_CONVERGENCE_TO_JOIN", stepId: fork.stepId, message: `A branch of fork "${fork.stepId}" reaches an END step before join "${joinStepId}"` });
          reportedNoConvergence = true;
        }
        return;
      }
      if (step.stepType === "PARALLEL_FORK") {
        if (!reportedNesting) {
          issues.push({ code: "NESTED_FORK_NOT_SUPPORTED", stepId: fork.stepId, message: `Nested PARALLEL_FORK "${stepId}" inside fork "${fork.stepId}" is not supported` });
          reportedNesting = true;
        }
        return;
      }
      if (step.stepType === "PARALLEL_JOIN") {
        if (!reportedNoConvergence) {
          issues.push({ code: "NO_CONVERGENCE_TO_JOIN", stepId: fork.stepId, message: `A branch of fork "${fork.stepId}" reaches join "${stepId}" instead of its own join "${joinStepId}"` });
          reportedNoConvergence = true;
        }
        return;
      }
      if (onStack.has(stepId)) {
        if (!reportedCycle) {
          issues.push({ code: "FORK_JOIN_CYCLE", stepId: fork.stepId, message: `A branch of fork "${fork.stepId}" contains a cycle at step "${stepId}"` });
          reportedCycle = true;
        }
        return;
      }
      if (fullyExplored.has(stepId)) return;
      const outgoing = outgoingByStep.get(stepId) ?? [];
      if (outgoing.length === 0) {
        if (!reportedNoConvergence) {
          issues.push({ code: "NO_CONVERGENCE_TO_JOIN", stepId: fork.stepId, message: `A branch of fork "${fork.stepId}" dead-ends at step "${stepId}" without reaching join "${joinStepId}"` });
          reportedNoConvergence = true;
        }
        return;
      }
      onStack.add(stepId);
      for (const transition of outgoing) visit(transition.toStepId);
      onStack.delete(stepId);
      fullyExplored.add(stepId);
    };
    for (const branch of autoBranches) visit(branch.toStepId);
  }
  for (const join of joinSteps) {
    if (!pairedJoinIds.has(join.stepId)) {
      issues.push({ code: "UNPAIRED_JOIN", stepId: join.stepId, message: `PARALLEL_JOIN "${join.stepId}" is not paired with any PARALLEL_FORK` });
    }
  }
  return issues;
}
const workflowDefinitionDataSchema = z.object({
  steps: z.array(workflowStepSchema).min(2, "Workflow must have at least START and END steps"),
  transitions: z.array(workflowTransitionSchema).min(1, "Workflow must have at least one transition"),
  triggers: z.array(workflowDefinitionTriggerSchema).optional(),
  // Event triggers for automatic workflow start
  queries: z.array(z.any()).optional(),
  // For Phase 7
  signals: z.array(z.any()).optional(),
  // For Phase 9
  timers: z.array(z.any()).optional()
  // For Phase 9
}).superRefine((definition, ctx) => {
  for (const issue of validateParallelForkJoin(definition)) {
    ctx.addIssue({
      code: "custom",
      path: ["steps"],
      message: `[${issue.code}] ${issue.message}`
    });
  }
});
const workflowMetadataSchema = z.object({
  tags: z.array(z.string().max(50)).optional(),
  category: z.string().max(100).optional(),
  icon: z.string().max(100).optional()
});
const dateOrNull = z.preprocess((value) => {
  if (value === void 0 || value === null || value === "") return null;
  const date = value instanceof Date ? value : new Date(String(value));
  return Number.isNaN(date.getTime()) ? null : date;
}, z.date().nullable());
const createWorkflowDefinitionSchema = z.object({
  workflowId: z.string().min(1).max(100).regex(/^[a-z0-9._-]+$/, "Workflow ID must contain only lowercase letters, numbers, dots, hyphens, and underscores"),
  workflowName: z.string().min(1).max(255),
  description: z.string().max(2e3).optional().nullable(),
  version: z.number().int().positive().default(1),
  definition: workflowDefinitionDataSchema,
  metadata: workflowMetadataSchema.optional().nullable(),
  enabled: z.boolean().default(true),
  effectiveFrom: dateOrNull.optional(),
  effectiveTo: dateOrNull.optional(),
  tenantId: uuid,
  organizationId: uuid,
  createdBy: z.string().max(255).optional().nullable()
});
const createWorkflowDefinitionInputSchema = z.object({
  workflowId: z.string().min(1).max(100).regex(/^[a-z0-9._-]+$/, "Workflow ID must contain only lowercase letters, numbers, dots, hyphens, and underscores"),
  workflowName: z.string().min(1).max(255),
  description: z.string().max(2e3).optional().nullable(),
  version: z.number().int().positive().default(1),
  definition: workflowDefinitionDataSchema,
  metadata: workflowMetadataSchema.optional().nullable(),
  enabled: z.boolean().default(true).optional()
});
const updateWorkflowDefinitionSchema = createWorkflowDefinitionSchema.partial().extend({
  id: uuid
});
const updateWorkflowDefinitionInputSchema = z.object({
  workflowId: z.string().min(1).max(100).optional(),
  workflowName: z.string().min(1).max(255).optional(),
  description: z.string().max(2e3).optional().nullable(),
  version: z.number().int().positive().optional(),
  definition: workflowDefinitionDataSchema.optional(),
  metadata: workflowMetadataSchema.optional().nullable(),
  enabled: z.boolean().optional(),
  effectiveFrom: dateOrNull.optional(),
  effectiveTo: dateOrNull.optional()
}).strict();
const workflowDefinitionFilterSchema = z.object({
  workflowId: z.string().optional(),
  workflowName: z.string().optional(),
  enabled: z.boolean().optional(),
  tenantId: uuid.optional(),
  organizationId: uuid.optional()
});
const workflowInstanceMetadataSchema = z.object({
  entityType: z.string().max(100).optional(),
  entityId: z.string().max(255).optional(),
  initiatedBy: z.string().max(255).optional(),
  labels: z.record(z.string(), z.string()).optional()
});
const createWorkflowInstanceSchema = z.object({
  definitionId: uuid,
  workflowId: z.string().min(1).max(100),
  version: z.number().int().positive(),
  status: workflowInstanceStatusSchema,
  currentStepId: z.string().min(1).max(100),
  context: z.record(z.string(), z.any()),
  correlationKey: z.string().max(255).optional().nullable(),
  metadata: workflowInstanceMetadataSchema.optional().nullable(),
  startedAt: z.coerce.date(),
  completedAt: dateOrNull.optional(),
  pausedAt: dateOrNull.optional(),
  cancelledAt: dateOrNull.optional(),
  errorMessage: z.string().max(5e3).optional().nullable(),
  errorDetails: z.any().optional().nullable(),
  retryCount: z.number().int().min(0).default(0),
  tenantId: uuid,
  organizationId: uuid
});
const updateWorkflowInstanceSchema = createWorkflowInstanceSchema.partial().extend({
  id: uuid
});
const workflowInstanceFilterSchema = z.object({
  definitionId: uuid.optional(),
  workflowId: z.string().optional(),
  status: workflowInstanceStatusSchema.optional(),
  correlationKey: z.string().optional(),
  currentStepId: z.string().optional(),
  tenantId: uuid.optional(),
  organizationId: uuid.optional()
});
const createStepInstanceSchema = z.object({
  workflowInstanceId: uuid,
  stepId: z.string().min(1).max(100),
  stepName: z.string().min(1).max(255),
  stepType: z.string().min(1).max(50),
  status: stepInstanceStatusSchema,
  inputData: z.any().optional().nullable(),
  outputData: z.any().optional().nullable(),
  errorData: z.any().optional().nullable(),
  enteredAt: dateOrNull.optional(),
  exitedAt: dateOrNull.optional(),
  executionTimeMs: z.number().int().min(0).optional().nullable(),
  retryCount: z.number().int().min(0).default(0),
  tenantId: uuid,
  organizationId: uuid
});
const updateStepInstanceSchema = createStepInstanceSchema.partial().extend({
  id: uuid
});
const stepInstanceFilterSchema = z.object({
  workflowInstanceId: uuid.optional(),
  stepId: z.string().optional(),
  status: stepInstanceStatusSchema.optional(),
  tenantId: uuid.optional(),
  organizationId: uuid.optional()
});
const createUserTaskSchema = z.object({
  workflowInstanceId: uuid,
  stepInstanceId: uuid,
  taskName: z.string().min(1).max(255),
  description: z.string().max(2e3).optional().nullable(),
  status: userTaskStatusSchema,
  formSchema: z.any().optional().nullable(),
  formData: z.any().optional().nullable(),
  assignedTo: z.string().max(255).optional().nullable(),
  assignedToRoles: z.array(z.string().max(100)).optional().nullable(),
  claimedBy: z.string().max(255).optional().nullable(),
  claimedAt: dateOrNull.optional(),
  dueDate: dateOrNull.optional(),
  escalatedAt: dateOrNull.optional(),
  escalatedTo: z.string().max(255).optional().nullable(),
  completedBy: z.string().max(255).optional().nullable(),
  completedAt: dateOrNull.optional(),
  comments: z.string().max(5e3).optional().nullable(),
  tenantId: uuid,
  organizationId: uuid
});
const updateUserTaskSchema = createUserTaskSchema.partial().extend({
  id: uuid
});
const userTaskFilterSchema = z.object({
  workflowInstanceId: uuid.optional(),
  status: userTaskStatusSchema.optional(),
  assignedTo: z.string().optional(),
  claimedBy: z.string().optional(),
  tenantId: uuid.optional(),
  organizationId: uuid.optional()
});
const createWorkflowEventSchema = z.object({
  workflowInstanceId: uuid,
  stepInstanceId: uuid.optional().nullable(),
  eventType: z.string().min(1).max(50),
  eventData: z.any(),
  occurredAt: z.coerce.date().optional(),
  userId: z.string().max(255).optional().nullable(),
  tenantId: uuid,
  organizationId: uuid
});
const workflowEventFilterSchema = z.object({
  workflowInstanceId: uuid.optional(),
  stepInstanceId: uuid.optional(),
  eventType: z.string().optional(),
  tenantId: uuid.optional(),
  organizationId: uuid.optional(),
  occurredAtFrom: z.date().optional(),
  occurredAtTo: z.date().optional()
});
const workflowExecutionContextSchema = z.looseObject({
  workflowId: z.string().min(1),
  version: z.number().int().positive().optional(),
  correlationKey: z.string().optional(),
  context: z.record(z.string(), z.any()).optional(),
  metadata: workflowInstanceMetadataSchema.optional(),
  tenantId: z.uuid("tenantId must be a valid UUID"),
  organizationId: z.uuid("organizationId must be a valid UUID"),
  initiatedBy: z.string().optional()
});
const startWorkflowInputSchema = z.object({
  workflowId: z.string().min(1),
  version: z.number().int().positive().optional(),
  correlationKey: z.string().optional(),
  initialContext: z.record(z.string(), z.any()).optional(),
  metadata: workflowInstanceMetadataSchema.optional()
});
const triggerFilterOperatorSchema = z.enum([
  "eq",
  "neq",
  "gt",
  "gte",
  "lt",
  "lte",
  "contains",
  "startsWith",
  "endsWith",
  "in",
  "notIn",
  "exists",
  "notExists",
  "regex"
]);
const triggerFilterConditionSchema = z.object({
  field: z.string().min(1).max(255, "Field path must be at most 255 characters"),
  operator: triggerFilterOperatorSchema,
  value: z.any()
});
const triggerContextMappingSchema = z.object({
  targetKey: z.string().min(1).max(100, "Target key must be at most 100 characters"),
  sourceExpression: z.string().min(1).max(255, "Source expression must be at most 255 characters"),
  defaultValue: z.any().optional()
});
const eventTriggerConfigSchema = z.object({
  filterConditions: z.array(triggerFilterConditionSchema).max(20, "Maximum 20 filter conditions allowed").optional(),
  contextMapping: z.array(triggerContextMappingSchema).max(50, "Maximum 50 context mappings allowed").optional(),
  debounceMs: z.number().int().min(0).max(36e5, "Debounce cannot exceed 1 hour").optional(),
  maxConcurrentInstances: z.number().int().min(1).max(1e3, "Max concurrent instances must be between 1 and 1000").optional()
});
const eventPatternSchema = z.string().min(1, "Event pattern is required").max(255, "Event pattern must be at most 255 characters").regex(
  /^(\*|[a-z0-9_]+(\.[a-z0-9_*]+)*)$/i,
  'Event pattern must be "*" or a dot-separated pattern with optional wildcards (e.g., "customers.people.created", "sales.orders.*")'
);
const createEventTriggerSchema = z.object({
  name: z.string().min(1).max(255),
  description: z.string().max(2e3).optional().nullable(),
  workflowDefinitionId: uuid,
  eventPattern: eventPatternSchema,
  config: eventTriggerConfigSchema.optional().nullable(),
  enabled: z.boolean().default(true),
  priority: z.number().int().min(0).max(9999).default(0),
  tenantId: uuid,
  organizationId: uuid,
  createdBy: z.string().max(255).optional().nullable()
});
const createEventTriggerInputSchema = z.object({
  name: z.string().min(1).max(255),
  description: z.string().max(2e3).optional().nullable(),
  workflowDefinitionId: uuid,
  eventPattern: eventPatternSchema,
  config: eventTriggerConfigSchema.optional().nullable(),
  enabled: z.boolean().default(true).optional(),
  priority: z.number().int().min(0).max(9999).default(0).optional()
});
const updateEventTriggerSchema = createEventTriggerSchema.partial().extend({
  id: uuid
});
const updateEventTriggerInputSchema = z.object({
  name: z.string().min(1).max(255).optional(),
  description: z.string().max(2e3).optional().nullable(),
  workflowDefinitionId: uuid.optional(),
  eventPattern: eventPatternSchema.optional(),
  config: eventTriggerConfigSchema.optional().nullable(),
  enabled: z.boolean().optional(),
  priority: z.number().int().min(0).max(9999).optional()
}).strict();
const eventTriggerFilterSchema = z.object({
  name: z.string().optional(),
  workflowDefinitionId: uuid.optional(),
  eventPattern: z.string().optional(),
  enabled: z.boolean().optional(),
  tenantId: uuid.optional(),
  organizationId: uuid.optional()
});
export {
  activityDefinitionSchema,
  activityRetryPolicySchema,
  activityTypeSchema,
  callApiConfigSchema,
  callWebhookConfigSchema,
  createEventTriggerInputSchema,
  createEventTriggerSchema,
  createStepInstanceSchema,
  createUserTaskSchema,
  createWorkflowDefinitionInputSchema,
  createWorkflowDefinitionSchema,
  createWorkflowEventSchema,
  createWorkflowInstanceSchema,
  escalationActionSchema,
  escalationTriggerSchema,
  eventPatternSchema,
  eventTriggerConfigSchema,
  eventTriggerFilterSchema,
  isFutureIsoDateString,
  isValidDurationString,
  isValidIsoDateString,
  localizedMessageSchema,
  retryPolicySchema,
  startPreConditionSchema,
  startWorkflowInputSchema,
  stepInstanceFilterSchema,
  stepInstanceStatusSchema,
  subWorkflowConfigSchema,
  transitionConditionSchema,
  transitionTriggerSchema,
  triggerContextMappingSchema,
  triggerFilterConditionSchema,
  triggerFilterOperatorSchema,
  updateEventTriggerInputSchema,
  updateEventTriggerSchema,
  updateStepInstanceSchema,
  updateUserTaskSchema,
  updateWorkflowDefinitionInputSchema,
  updateWorkflowDefinitionSchema,
  updateWorkflowInstanceSchema,
  userTaskConfigSchema,
  userTaskFilterSchema,
  userTaskStatusSchema,
  validateParallelForkJoin,
  workflowBranchInstanceStatusSchema,
  workflowDefinitionDataSchema,
  workflowDefinitionFilterSchema,
  workflowDefinitionTriggerSchema,
  workflowEventFilterSchema,
  workflowExecutionContextSchema,
  workflowInstanceFilterSchema,
  workflowInstanceMetadataSchema,
  workflowInstanceStatusSchema,
  workflowMetadataSchema,
  workflowStepSchema,
  workflowStepTypeSchema,
  workflowTransitionSchema
};
//# sourceMappingURL=validators.js.map
