import {
  OWNING_DELETE_OPS_EVENT_BUS_ENV_VAR
} from "./chunk-VESULYQQ.mjs";
import {
  defaultTableName,
  dynamoClient
} from "./chunk-TRY7JGWO.mjs";
import {
  require_lib
} from "./chunk-KMEWULMX.mjs";
import {
  __toESM
} from "./chunk-LZOMFHX3.mjs";

// src/workflows/control-plane/owning-delete-cascade/finalize.handler.ts
var import_workflows2 = __toESM(require_lib());
import { randomUUID } from "crypto";
import {
  EventBridgeClient,
  PutEventsCommand
} from "@aws-sdk/client-eventbridge";

// src/data/operations/control/owning-delete/owning-delete-finalize-operation.ts
var import_workflows = __toESM(require_lib());
import {
  ConditionalCheckFailedException,
  DeleteItemCommand
} from "@aws-sdk/client-dynamodb";
async function finalizeOwningDeleteOperation(params) {
  const { ownerType, ownerId, tenantId, tableName } = params;
  if (!ownerId || ownerId.length === 0) {
    throw new Error("finalizeOwningDeleteOperation: ownerId is required");
  }
  const partitionKey = buildOwningCanonicalPartitionKey({
    ownerType,
    ownerId,
    tenantId
  });
  const resolvedTableName = tableName ?? defaultTableName;
  try {
    await dynamoClient.send(
      new DeleteItemCommand({
        TableName: resolvedTableName,
        Key: {
          PK: { S: partitionKey },
          SK: { S: "CURRENT" }
        },
        ConditionExpression: "attribute_exists(PK) AND #lifecycleState = :deleting",
        ExpressionAttributeNames: {
          "#lifecycleState": "lifecycleState"
        },
        ExpressionAttributeValues: {
          ":deleting": { S: "deleting" }
        }
      })
    );
    return { deleted: true };
  } catch (err) {
    if (err instanceof ConditionalCheckFailedException) {
      return { deleted: false };
    }
    throw err;
  }
}
function buildOwningCanonicalPartitionKey(params) {
  switch (params.ownerType) {
    case import_workflows.OWNING_ENTITY_TYPE.Workspace:
      if (!params.tenantId || params.tenantId.length === 0) {
        throw new Error(
          "finalizeOwningDeleteOperation: tenantId is required for Workspace owners"
        );
      }
      return `TID#${params.tenantId}#WORKSPACE#ID#${params.ownerId}`;
    case import_workflows.OWNING_ENTITY_TYPE.User:
      return `USER#ID#${params.ownerId}`;
    default: {
      const exhaustive = params.ownerType;
      throw new Error(
        `finalizeOwningDeleteOperation: unsupported ownerType '${String(
          exhaustive
        )}'`
      );
    }
  }
}

// src/workflows/control-plane/owning-delete-cascade/finalize.handler.ts
var cachedClient;
function defaultEventBridgeClient() {
  if (cachedClient === void 0) {
    cachedClient = new EventBridgeClient({});
  }
  return cachedClient;
}
var handler = async (input, deps = {}) => {
  const finalize = await finalizeOwningDeleteOperation({
    ownerType: input.ownerType,
    ownerId: input.ownerId,
    tenantId: input.tenantId
  });
  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;
  if (finalize.deleted) {
    const busName = process.env[OWNING_DELETE_OPS_EVENT_BUS_ENV_VAR];
    if (!busName) {
      throw new Error(
        `owning-delete cascade finalize: ${OWNING_DELETE_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: "owning-delete-cascade" },
      occurredAt: completedAt,
      envelopeVersion: import_workflows2.ENVELOPE_VERSION,
      payload: {
        ownerType: input.ownerType,
        ownerId: input.ownerId,
        tenantId: input.tenantId,
        chunkCount: input.chunkCount,
        projectionsRemoved: input.projectionsRemoved,
        durationMs,
        completedAt
      }
    };
    const result = await bridge.send(
      new PutEventsCommand({
        Entries: [
          {
            EventBusName: busName,
            Source: import_workflows2.OPENHI_OPS_SOURCE,
            DetailType: import_workflows2.ControlPlaneOwningDeleteCompleteV1.detailType,
            Detail: JSON.stringify(envelope)
          }
        ]
      })
    );
    if ((result.FailedEntryCount ?? 0) > 0) {
      const failed = result.Entries?.[0];
      throw new Error(
        `owning-delete cascade finalize: terminal event publish failed on bus ${busName}: ${failed?.ErrorCode ?? "unknown"} \u2014 ${failed?.ErrorMessage ?? "no error message"}`
      );
    }
  }
  return {
    ownerType: input.ownerType,
    ownerId: input.ownerId,
    tenantId: input.tenantId,
    projectionsRemoved: input.projectionsRemoved,
    chunkCount: input.chunkCount,
    durationMs,
    completedAt,
    canonicalDeleted: finalize.deleted
  };
};
export {
  OWNING_DELETE_OPS_EVENT_BUS_ENV_VAR,
  handler
};
//# sourceMappingURL=finalize.handler.mjs.map