import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows").child({ component: "event-trigger" });
const metadata = {
  event: "*",
  // Subscribe to ALL events
  persistent: true,
  // Ensure reliability
  id: "workflows:event-trigger"
};
const EXCLUDED_EVENT_PREFIXES = [
  "query_index.",
  // Internal indexing events
  "search.",
  // Internal search events
  "workflows.",
  // Workflow internal events (avoid recursion)
  "cache.",
  // Cache events
  "queue."
  // Queue events
];
function isExcludedEvent(eventName) {
  return EXCLUDED_EVENT_PREFIXES.some((prefix) => eventName.startsWith(prefix));
}
async function handle(payload, ctx) {
  const eventName = ctx.eventName;
  if (!eventName) {
    logger.warn("Skipping trigger evaluation because subscriber context is missing eventName");
    return;
  }
  if (isExcludedEvent(eventName)) {
    return;
  }
  const eventPayload = 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;
  }
  let em;
  let container;
  try {
    em = ctx.resolve("em");
    container = {
      resolve: ctx.resolve,
      // Provide minimal AwilixContainer interface for type compatibility
      cradle: new Proxy({}, {
        get: (_target, prop) => ctx.resolve(prop)
      })
    };
  } catch (error) {
    logger.warn("Cannot resolve dependencies for event", { event: eventName, err: error });
    return;
  }
  const { processEventTriggers } = await import("../lib/event-trigger-service.js");
  try {
    const result = await processEventTriggers(em, container, {
      eventName,
      payload: eventPayload,
      tenantId,
      organizationId
    });
    logger.debug("Evaluated triggers", {
      event: eventName,
      tenantId,
      organizationId,
      matched: result.triggered + result.skipped + result.errors.length,
      triggered: result.triggered,
      skipped: result.skipped,
      errors: result.errors.length
    });
    if (result.triggered > 0) {
      logger.info("Triggered workflows for event", {
        event: eventName,
        triggered: result.triggered,
        skipped: result.skipped,
        errors: result.errors.length
      });
    }
    if (result.errors.length > 0) {
      for (const err of result.errors) {
        logger.error("Trigger failed", { triggerId: err.triggerId, err: err.error });
      }
    }
  } catch (error) {
    logger.error("Error processing triggers for event", { event: eventName, err: error });
  }
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=event-trigger.js.map
