import {
  RENAME_CASCADE_OPS_EVENT_BUS_ENV_VAR
} from "./chunk-D2Y6DDOC.mjs";
import {
  require_lib
} from "./chunk-KMEWULMX.mjs";
import {
  __toESM
} from "./chunk-LZOMFHX3.mjs";

// src/workflows/control-plane/rename-cascade/rename-finalize.handler.ts
var import_workflows = __toESM(require_lib());
import { randomUUID } from "crypto";
import {
  EventBridgeClient,
  PutEventsCommand
} from "@aws-sdk/client-eventbridge";
var cachedClient;
function defaultEventBridgeClient() {
  if (cachedClient === void 0) {
    cachedClient = new EventBridgeClient({});
  }
  return cachedClient;
}
var handler = async (input, deps = {}) => {
  const now = (deps.now ?? (() => /* @__PURE__ */ new Date()))();
  const completedAt = now.toISOString();
  const startedAtMs = Date.parse(input.startedAt);
  const durationMs = Number.isFinite(startedAtMs) ? Math.max(0, now.getTime() - startedAtMs) : 0;
  const busName = process.env[RENAME_CASCADE_OPS_EVENT_BUS_ENV_VAR];
  if (!busName) {
    throw new Error(
      `rename-cascade finalize: ${RENAME_CASCADE_OPS_EVENT_BUS_ENV_VAR} env var is not set`
    );
  }
  const bridge = deps.eventBridgeClient ?? defaultEventBridgeClient();
  const eventId = (deps.eventIdGenerator ?? randomUUID)();
  const envelope = {
    eventId,
    attempt: 1,
    correlationId: input.correlationId ?? eventId,
    causationId: input.causationId ?? input.eventId ?? null,
    actor: { system: "rename-cascade" },
    occurredAt: completedAt,
    envelopeVersion: import_workflows.ENVELOPE_VERSION,
    payload: {
      entityType: input.entityType,
      entityId: input.entityId,
      tenantId: input.tenantId,
      newName: input.newName,
      chunkCount: input.chunkCount,
      itemsRewritten: input.itemsRewritten,
      durationMs,
      completedAt
    }
  };
  const result = await bridge.send(
    new PutEventsCommand({
      Entries: [
        {
          EventBusName: busName,
          Source: import_workflows.OPENHI_OPS_SOURCE,
          DetailType: import_workflows.ControlPlaneRenameCompleteV1.detailType,
          Detail: JSON.stringify(envelope)
        }
      ]
    })
  );
  if ((result.FailedEntryCount ?? 0) > 0) {
    const failed = result.Entries?.[0];
    throw new Error(
      `rename-cascade finalize: terminal event publish failed on bus ${busName}: ${failed?.ErrorCode ?? "unknown"} \u2014 ${failed?.ErrorMessage ?? "no error message"}`
    );
  }
  return {
    entityType: input.entityType,
    entityId: input.entityId,
    tenantId: input.tenantId,
    newName: input.newName,
    itemsRewritten: input.itemsRewritten,
    chunkCount: input.chunkCount,
    durationMs,
    completedAt
  };
};
export {
  RENAME_CASCADE_OPS_EVENT_BUS_ENV_VAR,
  handler
};
//# sourceMappingURL=rename-finalize.handler.mjs.map