// runtime/base-classes/lifecycle-events.ts
import { randomUUID } from "crypto";
var SYSTEM_FIELDS = /* @__PURE__ */ new Set([
  "id",
  "createdAt",
  "updatedAt",
  "deletedAt"
]);
function entitySnapshot(entity) {
  const snap = {};
  for (const [key, value] of Object.entries(entity)) {
    if (!SYSTEM_FIELDS.has(key)) {
      snap[key] = value;
    }
  }
  return snap;
}
function diffSnapshots(before, after) {
  const changes = [];
  const allKeys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
  for (const key of allKeys) {
    if (SYSTEM_FIELDS.has(key)) continue;
    const oldVal = before[key];
    const newVal = after[key];
    if (oldVal !== newVal && JSON.stringify(oldVal) !== JSON.stringify(newVal)) {
      changes.push({ field: key, oldValue: oldVal, newValue: newVal });
    }
  }
  return changes;
}
function buildLifecycleEvent(entityName, action, entityId, snapshot) {
  return {
    id: randomUUID(),
    type: `${entityName}.${action}`,
    aggregateId: entityId,
    aggregateType: entityName,
    payload: snapshot ? { snapshot } : {},
    occurredAt: /* @__PURE__ */ new Date(),
    metadata: { category: "lifecycle" }
  };
}
function buildChangeEvents(entityName, entityId, changes) {
  return changes.map((c) => ({
    id: randomUUID(),
    type: `${entityName}.field_changed`,
    aggregateId: entityId,
    aggregateType: entityName,
    payload: {
      fieldName: c.field,
      oldValue: c.oldValue,
      newValue: c.newValue
    },
    occurredAt: /* @__PURE__ */ new Date(),
    metadata: { category: "change" }
  }));
}
async function emitSafely(eventBus, events) {
  if (!eventBus || events.length === 0) return;
  try {
    if (events.length === 1) {
      const only = events[0];
      if (!only) return;
      await eventBus.publish(only);
    } else {
      await eventBus.publishMany(events);
    }
  } catch {
    console.warn(`[lifecycle-events] failed to emit ${events.length} event(s)`);
  }
}

export {
  entitySnapshot,
  diffSnapshots,
  buildLifecycleEvent,
  buildChangeEvents,
  emitSafely
};
//# sourceMappingURL=chunk-KYR3B3OW.js.map