import { matchWildcardPattern } from "@open-mercato/shared/lib/patterns/wildcard";
import { createLogger } from "../logger/index.js";
const logger = createLogger("shared").child({ component: "crud" });
function matchesEventPattern(pattern, eventId) {
  return matchWildcardPattern(eventId, pattern);
}
function collectSyncSubscribers(allSyncSubscribers, eventId) {
  return allSyncSubscribers.filter((s) => matchesEventPattern(s.metadata.event, eventId)).sort((a, b) => (a.metadata.priority ?? 50) - (b.metadata.priority ?? 50));
}
async function runSyncBeforeEvent(subscribers, payload, ctx) {
  let currentPayload = payload.payload;
  for (const subscriber of subscribers) {
    const result = await subscriber.handler({ ...payload, payload: currentPayload }, ctx);
    if (result?.ok === false) {
      const body = result.body ?? { error: result.message ?? "Operation blocked", subscriberId: subscriber.metadata.id };
      return { ok: false, errorBody: body, errorStatus: result.status ?? 422 };
    }
    if (result?.modifiedPayload) {
      currentPayload = { ...currentPayload, ...result.modifiedPayload };
    }
  }
  return { ok: true, modifiedPayload: currentPayload !== payload.payload ? currentPayload : void 0 };
}
async function runSyncAfterEvent(subscribers, payload, ctx) {
  for (const subscriber of subscribers) {
    try {
      await subscriber.handler(payload, ctx);
    } catch (error) {
      logger.error("Sync-event after-subscriber failed", { subscriberId: subscriber.metadata.id, err: error });
    }
  }
}
export {
  collectSyncSubscribers,
  matchesEventPattern,
  runSyncAfterEvent,
  runSyncBeforeEvent
};
//# sourceMappingURL=sync-event-runner.js.map
