import {
  getEventMetadata
} from "./chunk-BGULBWKJ.js";
import {
  eventPayloadSchemas
} from "./chunk-JRQO2IOF.js";
import {
  MissingTenantIdError
} from "./chunk-V4AF6DI4.js";
import {
  EVENTS_MULTI_TENANT,
  EVENT_BUS
} from "./chunk-H5NH7KPE.js";
import {
  __decorateClass,
  __decorateParam
} from "./chunk-2E224ZSN.js";

// runtime/subsystems/events/generated/bus.ts
import { Injectable, Inject } from "@nestjs/common";
import { randomUUID } from "crypto";
var TypedEventBus = class {
  constructor(bus, multiTenant) {
    this.bus = bus;
    this.multiTenant = multiTenant;
  }
  bus;
  multiTenant;
  async publish(type, aggregateId, payload, opts) {
    const meta = getEventMetadata(type);
    const flag = process.env["CODEGEN_EVENT_VALIDATE"];
    const shouldValidate = flag === void 0 ? true : flag !== "false" && flag !== "0";
    if (shouldValidate) {
      const schema = eventPayloadSchemas[type];
      if (schema) {
        const check = schema.safeParse(payload);
        if (!check.success) {
          console.warn(
            `[TypedEventBus] payload validation failed for ${String(type)}:`,
            check.error.issues
          );
        }
      }
    }
    const tenantId = opts?.metadata?.["tenantId"];
    if (this.multiTenant && (tenantId === void 0 || tenantId === null)) {
      throw new MissingTenantIdError(type);
    }
    const aggregateType = meta.aggregate ?? meta.source ?? meta.destination ?? type;
    const baseMetadata = { ...opts?.metadata ?? {} };
    if (meta.tier === "audit") {
      if (baseMetadata["pool"] !== void 0 || baseMetadata["direction"] !== void 0) {
        console.debug(
          `[TypedEventBus] tier:audit event '${String(type)}' had pool/direction in opts.metadata; overriding to null.`
        );
      }
      baseMetadata["pool"] = null;
      baseMetadata["direction"] = null;
      baseMetadata["tier"] = "audit";
    } else {
      baseMetadata["pool"] = meta.pool;
      baseMetadata["direction"] = meta.direction;
      baseMetadata["tier"] = "domain";
    }
    baseMetadata["version"] = meta.version;
    await this.bus.publish(
      {
        id: randomUUID(),
        type,
        aggregateId,
        aggregateType,
        payload,
        occurredAt: /* @__PURE__ */ new Date(),
        metadata: baseMetadata
      },
      opts?.tx
    );
  }
  subscribe(type, handler) {
    return this.bus.subscribe(type, handler);
  }
};
TypedEventBus = __decorateClass([
  Injectable(),
  __decorateParam(0, Inject(EVENT_BUS)),
  __decorateParam(1, Inject(EVENTS_MULTI_TENANT))
], TypedEventBus);

export {
  TypedEventBus
};
//# sourceMappingURL=chunk-GM3RMJIJ.js.map