import { z } from "zod";
import {
  validateConditionExpressionForApi,
  validateActionsForApi,
  isSafeExpression
} from "../lib/payload-validation.js";
const uuid = z.uuid();
const ruleTypeSchema = z.enum(["GUARD", "VALIDATION", "CALCULATION", "ACTION", "ASSIGNMENT"]);
const conditionTypeSchema = z.enum(["EXPRESSION", "GROUP"]);
const logicalOperatorSchema = z.enum(["AND", "OR", "NOT"]);
const comparisonOperatorSchema = z.enum([
  "=",
  "==",
  "!=",
  ">",
  ">=",
  "<",
  "<=",
  "IN",
  "NOT_IN",
  "CONTAINS",
  "NOT_CONTAINS",
  "STARTS_WITH",
  "ENDS_WITH",
  "MATCHES",
  "IS_EMPTY",
  "IS_NOT_EMPTY"
]);
const dataTypeSchema = z.enum(["STRING", "NUMBER", "BOOLEAN", "DATE", "ARRAY", "OBJECT"]);
const actionTriggerSchema = z.enum(["ON_SUCCESS", "ON_FAILURE", "ALWAYS"]);
const executionResultSchema = z.enum(["SUCCESS", "FAILURE", "ERROR"]);
function createConditionExpressionSchema(t) {
  return z.any().optional().nullable().superRefine((val, ctx) => {
    if (val === null || val === void 0) return;
    if (!isSafeExpression(val)) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "Condition expression exceeds safety limits (max depth: 10, max rules per group: 50, max field path length: 200)"
      });
      return;
    }
    const result = validateConditionExpressionForApi(val, t);
    if (!result.valid) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: result.error || "Invalid condition expression"
      });
    }
  });
}
const conditionExpressionSchema = createConditionExpressionSchema();
const actionSchema = z.object({
  type: z.string().min(1),
  config: z.record(z.string(), z.any()).optional()
});
function createActionsArraySchema(t) {
  return z.array(actionSchema).optional().nullable().superRefine((val, ctx) => {
    if (!val || Array.isArray(val) && val.length === 0) return;
    const result = validateActionsForApi(val, "actions", t);
    if (!result.valid) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: result.error || "Invalid actions"
      });
    }
  });
}
const actionsArraySchema = createActionsArraySchema();
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 EFFECTIVE_DATE_RANGE_DEFAULT_MESSAGE = "Effective To must be later than Effective From";
function toDateOrNull(value) {
  if (value === void 0 || value === null || value === "") return null;
  if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
  const parsed = new Date(String(value));
  return Number.isNaN(parsed.getTime()) ? null : parsed;
}
function refineEffectiveDateRange(data, ctx, message = EFFECTIVE_DATE_RANGE_DEFAULT_MESSAGE) {
  const from = toDateOrNull(data.effectiveFrom);
  const to = toDateOrNull(data.effectiveTo);
  if (from === null || to === null) return;
  if (to.getTime() <= from.getTime()) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message,
      path: ["effectiveTo"]
    });
  }
}
const businessRuleBaseFields = {
  ruleId: z.string().min(1).max(50),
  ruleName: z.string().min(1).max(200),
  description: z.string().max(5e3).optional().nullable(),
  ruleType: ruleTypeSchema,
  ruleCategory: z.string().max(50).optional().nullable(),
  entityType: z.string().min(1).max(50),
  eventType: z.string().max(50).optional().nullable(),
  enabled: z.boolean().optional().default(true),
  priority: z.number().int().min(0).max(9999).optional().default(100),
  version: z.number().int().min(1).optional().default(1),
  effectiveFrom: dateOrNull.optional(),
  effectiveTo: dateOrNull.optional(),
  tenantId: uuid,
  organizationId: uuid,
  createdBy: z.string().max(50).optional().nullable()
};
const createBusinessRuleSchema = z.object({
  ...businessRuleBaseFields,
  conditionExpression: conditionExpressionSchema.optional().nullable(),
  successActions: actionsArraySchema,
  failureActions: actionsArraySchema
}).superRefine((data, ctx) => refineEffectiveDateRange(data, ctx));
const updateBusinessRuleSchema = z.object({
  ...businessRuleBaseFields,
  conditionExpression: conditionExpressionSchema.optional().nullable(),
  successActions: actionsArraySchema,
  failureActions: actionsArraySchema
}).omit({ tenantId: true, organizationId: true, createdBy: true }).partial().extend({ id: uuid }).superRefine((data, ctx) => refineEffectiveDateRange(data, ctx));
function createLocalizedBusinessRuleSchema(t) {
  const conditionSchema = createConditionExpressionSchema(t);
  const actionsSchema = createActionsArraySchema(t);
  const message = t("business_rules.rules.form.errors.effectiveToBeforeFrom");
  return z.object({
    ...businessRuleBaseFields,
    conditionExpression: conditionSchema.optional().nullable(),
    successActions: actionsSchema,
    failureActions: actionsSchema
  }).superRefine((data, ctx) => refineEffectiveDateRange(data, ctx, message));
}
function createLocalizedUpdateBusinessRuleSchema(t) {
  const conditionSchema = createConditionExpressionSchema(t);
  const actionsSchema = createActionsArraySchema(t);
  const message = t("business_rules.rules.form.errors.effectiveToBeforeFrom");
  return z.object({
    ...businessRuleBaseFields,
    conditionExpression: conditionSchema.optional().nullable(),
    successActions: actionsSchema,
    failureActions: actionsSchema
  }).omit({ tenantId: true, organizationId: true, createdBy: true }).partial().extend({ id: uuid }).superRefine((data, ctx) => refineEffectiveDateRange(data, ctx, message));
}
const businessRuleFilterSchema = z.object({
  ruleId: z.string().optional(),
  ruleName: z.string().optional(),
  ruleType: ruleTypeSchema.optional(),
  ruleCategory: z.string().optional(),
  entityType: z.string().optional(),
  eventType: z.string().optional(),
  enabled: z.boolean().optional(),
  tenantId: uuid.optional(),
  organizationId: uuid.optional()
});
const createRuleExecutionLogSchema = z.object({
  ruleId: uuid,
  entityId: uuid,
  entityType: z.string().min(1).max(50),
  executionResult: executionResultSchema,
  inputContext: z.any().optional().nullable(),
  outputContext: z.any().optional().nullable(),
  errorMessage: z.string().optional().nullable(),
  executionTimeMs: z.number().int().min(0),
  executedAt: z.date().optional(),
  tenantId: uuid,
  organizationId: uuid.optional().nullable(),
  executedBy: z.string().max(50).optional().nullable()
});
const ruleExecutionLogFilterSchema = z.object({
  ruleId: uuid.optional(),
  entityId: uuid.optional(),
  entityType: z.string().optional(),
  executionResult: executionResultSchema.optional(),
  tenantId: uuid.optional(),
  organizationId: uuid.optional(),
  executedBy: z.string().optional(),
  executedAtFrom: z.date().optional(),
  executedAtTo: z.date().optional()
});
const createRuleSetSchema = z.object({
  setId: z.string().min(1).max(50),
  setName: z.string().min(1).max(200),
  description: z.string().max(5e3).optional().nullable(),
  enabled: z.boolean().optional().default(true),
  tenantId: uuid,
  organizationId: uuid,
  createdBy: z.string().max(50).optional().nullable()
});
const updateRuleSetSchema = createRuleSetSchema.omit({ tenantId: true, organizationId: true, createdBy: true }).partial().extend({ id: uuid });
const ruleSetFilterSchema = z.object({
  setId: z.string().optional(),
  setName: z.string().optional(),
  enabled: z.boolean().optional(),
  tenantId: uuid.optional(),
  organizationId: uuid.optional()
});
const createRuleSetMemberSchema = z.object({
  ruleSetId: uuid,
  ruleId: uuid,
  sequence: z.number().int().min(0).optional().default(0),
  enabled: z.boolean().optional().default(true),
  tenantId: uuid,
  organizationId: uuid
});
const updateRuleSetMemberSchema = z.object({
  id: uuid,
  sequence: z.number().int().min(0).optional(),
  enabled: z.boolean().optional()
});
const ruleSetMemberFilterSchema = z.object({
  ruleSetId: uuid.optional(),
  ruleId: uuid.optional(),
  enabled: z.boolean().optional(),
  tenantId: uuid.optional(),
  organizationId: uuid.optional()
});
const ruleEngineContextSchema = z.looseObject({
  entityType: z.string().min(1, "entityType is required"),
  entityId: z.string().optional(),
  eventType: z.string().optional(),
  data: z.any(),
  user: z.looseObject({
    id: z.string().optional(),
    email: z.string().optional(),
    role: z.string().optional()
  }).optional(),
  tenant: z.looseObject({
    id: z.string().optional()
  }).optional(),
  organization: z.looseObject({
    id: z.string().optional()
  }).optional(),
  tenantId: z.uuid("tenantId must be a valid UUID"),
  organizationId: z.uuid("organizationId must be a valid UUID"),
  executedBy: z.string().optional(),
  dryRun: z.boolean().optional()
});
const ruleDiscoveryOptionsSchema = z.object({
  entityType: z.string().min(1, "entityType is required"),
  eventType: z.string().optional(),
  tenantId: z.uuid("tenantId must be a valid UUID"),
  organizationId: z.uuid("organizationId must be a valid UUID"),
  ruleType: ruleTypeSchema.optional()
});
const directRuleExecutionContextSchema = z.object({
  ruleId: z.uuid("ruleId must be a valid UUID"),
  data: z.any(),
  user: z.looseObject({
    id: z.string().optional(),
    email: z.string().optional(),
    role: z.string().optional()
  }).optional(),
  tenantId: z.uuid("tenantId must be a valid UUID"),
  organizationId: z.uuid("organizationId must be a valid UUID"),
  executedBy: z.string().optional(),
  dryRun: z.boolean().optional(),
  entityType: z.string().optional(),
  entityId: z.string().optional(),
  eventType: z.string().optional()
});
const ruleIdExecutionContextSchema = z.object({
  ruleId: z.string().min(1, "ruleId must be a non-empty string").max(50),
  data: z.any(),
  user: z.looseObject({
    id: z.string().optional(),
    email: z.string().optional(),
    role: z.string().optional()
  }).optional(),
  tenantId: z.uuid("tenantId must be a valid UUID"),
  organizationId: z.uuid("organizationId must be a valid UUID"),
  executedBy: z.string().optional(),
  dryRun: z.boolean().optional(),
  entityType: z.string().optional(),
  entityId: z.string().optional(),
  eventType: z.string().optional()
});
export {
  EFFECTIVE_DATE_RANGE_DEFAULT_MESSAGE,
  actionSchema,
  actionTriggerSchema,
  actionsArraySchema,
  businessRuleFilterSchema,
  comparisonOperatorSchema,
  conditionExpressionSchema,
  conditionTypeSchema,
  createBusinessRuleSchema,
  createLocalizedBusinessRuleSchema,
  createLocalizedUpdateBusinessRuleSchema,
  createRuleExecutionLogSchema,
  createRuleSetMemberSchema,
  createRuleSetSchema,
  dataTypeSchema,
  directRuleExecutionContextSchema,
  executionResultSchema,
  logicalOperatorSchema,
  refineEffectiveDateRange,
  ruleDiscoveryOptionsSchema,
  ruleEngineContextSchema,
  ruleExecutionLogFilterSchema,
  ruleIdExecutionContextSchema,
  ruleSetFilterSchema,
  ruleSetMemberFilterSchema,
  ruleTypeSchema,
  updateBusinessRuleSchema,
  updateRuleSetMemberSchema,
  updateRuleSetSchema
};
//# sourceMappingURL=validators.js.map
