import { executeRules, resolveBusinessRuleDiscoveryCache } from "../lib/rule-engine.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("business_rules").child({ component: "crud-rule-trigger" });
const metadata = {
  event: "*",
  persistent: true,
  id: "business_rules:crud-rule-trigger"
};
const EXCLUDED_EVENT_PREFIXES = [
  "query_index.",
  "search.",
  "business_rules.",
  "cache.",
  "queue.",
  "workflows."
];
function isExcludedEvent(eventName) {
  return EXCLUDED_EVENT_PREFIXES.some((prefix) => eventName.startsWith(prefix));
}
function parseEventName(eventName) {
  const parts = eventName.split(".");
  if (parts.length < 3) return null;
  const eventType = parts[parts.length - 1];
  const entityType = parts.slice(0, -1).join(".");
  return { entityType, eventType };
}
async function handle(payload, ctx) {
  const eventName = ctx.eventName;
  if (!eventName) return;
  if (isExcludedEvent(eventName)) return;
  const parsed = parseEventName(eventName);
  if (!parsed) return;
  const data = payload && typeof payload === "object" ? payload : {};
  const tenantId = typeof ctx.tenantId === "string" && ctx.tenantId.length > 0 ? ctx.tenantId : void 0;
  const organizationId = typeof ctx.organizationId === "string" && ctx.organizationId.length > 0 ? ctx.organizationId : void 0;
  if (!tenantId || !organizationId) return;
  const em = ctx.resolve("em");
  const cache = resolveBusinessRuleDiscoveryCache(ctx.resolve);
  try {
    await executeRules(em, {
      entityType: parsed.entityType,
      eventType: parsed.eventType,
      data,
      tenantId,
      organizationId
    }, { cache });
  } catch (error) {
    logger.error("Rule execution failed for event", { event: eventName, err: error });
  }
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=crud-rule-trigger.js.map
