import {
  TRANSACT_WRITE_ITEM_LIMIT,
  executeMultiWrite
} from "./chunk-QJDHVMKT.mjs";
import {
  getDynamoControlService
} from "./chunk-EUIP2U5F.mjs";
import {
  require_lib
} from "./chunk-KMEWULMX.mjs";
import {
  __toESM
} from "./chunk-LZOMFHX3.mjs";

// src/data/operations/control/owning-delete/owning-delete-batch-delete-operation.ts
var OWNING_DELETE_CASCADE_CHUNK_SIZE = TRANSACT_WRITE_ITEM_LIMIT;
async function deleteOwningChildChunkOperation(params) {
  const { rows, tableName, token } = params;
  if (rows.length === 0) {
    return { rowsDeleted: 0, breakdown: {} };
  }
  if (rows.length > OWNING_DELETE_CASCADE_CHUNK_SIZE) {
    throw new Error(
      `deleteOwningChildChunkOperation: chunk has ${rows.length} rows; limit is ${OWNING_DELETE_CASCADE_CHUNK_SIZE}`
    );
  }
  const service = getDynamoControlService(tableName);
  const triples = rows.map((row) => ({
    entity: row.entity,
    action: "delete",
    item: { ...row.key }
  }));
  await executeMultiWrite({ service, triples, token });
  const breakdown = {};
  for (const row of rows) {
    breakdown[row.entity] = (breakdown[row.entity] ?? 0) + 1;
  }
  return { rowsDeleted: rows.length, breakdown };
}
function chunkOwningChildRows(rows) {
  const chunks = [];
  for (let i = 0; i < rows.length; i += OWNING_DELETE_CASCADE_CHUNK_SIZE) {
    chunks.push(rows.slice(i, i + OWNING_DELETE_CASCADE_CHUNK_SIZE));
  }
  return chunks;
}

// src/data/operations/control/owning-delete/owning-delete-list-child-projections-operation.ts
var import_workflows = __toESM(require_lib());
var OWNING_DELETE_PROJECTION_ENTITY = {
  MembershipUserProjection: "membershipUserProjection",
  MembershipWorkspaceProjection: "membershipWorkspaceProjection",
  RoleAssignmentUserProjection: "roleAssignmentUserProjection",
  RoleAssignmentWorkspaceProjection: "roleAssignmentWorkspaceProjection",
  ConfigurationUserProjection: "configurationUserProjection",
  ConfigurationWorkspaceProjection: "configurationWorkspaceProjection"
};
var DEFAULT_PAGE_SIZE = 100;
var ENTITY_SK_PREFIXES = {
  membershipUserProjection: "MEMBERSHIP#",
  membershipWorkspaceProjection: "MEMBERSHIP#",
  roleAssignmentUserProjection: "ROLEASSIGNMENT#",
  roleAssignmentWorkspaceProjection: "ROLEASSIGNMENT#",
  configurationUserProjection: "CONFIGURATION#",
  configurationWorkspaceProjection: "CONFIGURATION#"
};
var ENTITIES_FOR_OWNER = {
  Workspace: [
    "membershipWorkspaceProjection",
    "roleAssignmentWorkspaceProjection",
    "configurationWorkspaceProjection"
  ],
  User: [
    "membershipUserProjection",
    "roleAssignmentUserProjection",
    "configurationUserProjection"
  ]
};
async function listOwningChildProjectionsOperation(params) {
  const {
    ownerType,
    ownerId,
    tenantId,
    cursors = {},
    limit = DEFAULT_PAGE_SIZE,
    tableName
  } = params;
  if (!ownerId || ownerId.length === 0) {
    throw new Error("listOwningChildProjectionsOperation: ownerId is required");
  }
  if (ownerType === import_workflows.OWNING_ENTITY_TYPE.Workspace && (!tenantId || tenantId.length === 0)) {
    throw new Error(
      "listOwningChildProjectionsOperation: tenantId is required for Workspace owners"
    );
  }
  const service = getDynamoControlService(tableName);
  const entities = ENTITIES_FOR_OWNER[ownerType];
  const nextCursors = {};
  const items = [];
  for (const entityName of entities) {
    const priorCursor = cursors[entityName];
    if (priorCursor === null) {
      nextCursors[entityName] = null;
      continue;
    }
    const prefix = ENTITY_SK_PREFIXES[entityName];
    const page = await queryProjectionEntity({
      service,
      entityName,
      ownerType,
      ownerId,
      tenantId,
      prefix,
      cursor: priorCursor ?? null,
      limit
    });
    for (const row of page.items) {
      items.push(row);
    }
    nextCursors[entityName] = page.cursor;
  }
  const exhausted = Object.values(nextCursors).every((value) => value === null);
  return { items, cursors: nextCursors, exhausted };
}
async function queryProjectionEntity(params) {
  const {
    service,
    entityName,
    ownerType,
    ownerId,
    tenantId,
    prefix,
    cursor,
    limit
  } = params;
  const goOptions = { cursor, limit };
  switch (entityName) {
    case "membershipUserProjection": {
      const result = await service.entities.membershipUserProjection.query.record({ userId: ownerId }).begins({ sk: prefix }).go(goOptions);
      const items = (result.data ?? []).map(
        (row) => ({
          entity: entityName,
          key: { userId: row.userId, sk: row.sk }
        })
      );
      return { items, cursor: result.cursor ?? null };
    }
    case "membershipWorkspaceProjection": {
      if (ownerType !== import_workflows.OWNING_ENTITY_TYPE.Workspace || !tenantId) {
        return { items: [], cursor: null };
      }
      const result = await service.entities.membershipWorkspaceProjection.query.record({ tenantId, workspaceId: ownerId }).begins({ sk: prefix }).go(goOptions);
      const items = (result.data ?? []).map(
        (row) => ({
          entity: entityName,
          key: {
            tenantId: row.tenantId,
            workspaceId: row.workspaceId,
            sk: row.sk
          }
        })
      );
      return { items, cursor: result.cursor ?? null };
    }
    case "roleAssignmentUserProjection": {
      const result = await service.entities.roleAssignmentUserProjection.query.record({ userId: ownerId }).begins({ sk: prefix }).go(goOptions);
      const items = (result.data ?? []).map(
        (row) => ({
          entity: entityName,
          key: { userId: row.userId, sk: row.sk }
        })
      );
      return { items, cursor: result.cursor ?? null };
    }
    case "roleAssignmentWorkspaceProjection": {
      if (ownerType !== import_workflows.OWNING_ENTITY_TYPE.Workspace || !tenantId) {
        return { items: [], cursor: null };
      }
      const result = await service.entities.roleAssignmentWorkspaceProjection.query.record({ tenantId, workspaceId: ownerId }).begins({ sk: prefix }).go(goOptions);
      const items = (result.data ?? []).map(
        (row) => ({
          entity: entityName,
          key: {
            tenantId: row.tenantId,
            workspaceId: row.workspaceId,
            sk: row.sk
          }
        })
      );
      return { items, cursor: result.cursor ?? null };
    }
    case "configurationUserProjection": {
      const result = await service.entities.configurationUserProjection.query.record({ userId: ownerId }).begins({ sk: prefix }).go(goOptions);
      const items = (result.data ?? []).map(
        (row) => ({
          entity: entityName,
          key: { userId: row.userId, sk: row.sk }
        })
      );
      return { items, cursor: result.cursor ?? null };
    }
    case "configurationWorkspaceProjection": {
      if (ownerType !== import_workflows.OWNING_ENTITY_TYPE.Workspace || !tenantId) {
        return { items: [], cursor: null };
      }
      const result = await service.entities.configurationWorkspaceProjection.query.record({ tenantId, workspaceId: ownerId }).begins({ sk: prefix }).go(goOptions);
      const items = (result.data ?? []).map(
        (row) => ({
          entity: entityName,
          key: {
            tenantId: row.tenantId,
            workspaceId: row.workspaceId,
            sk: row.sk
          }
        })
      );
      return { items, cursor: result.cursor ?? null };
    }
    default: {
      const exhaustive = entityName;
      throw new Error(
        `listOwningChildProjectionsOperation: unsupported entity '${String(
          exhaustive
        )}'`
      );
    }
  }
}

export {
  deleteOwningChildChunkOperation,
  chunkOwningChildRows,
  OWNING_DELETE_PROJECTION_ENTITY,
  listOwningChildProjectionsOperation
};
//# sourceMappingURL=chunk-Q3MKITPY.mjs.map