import {
  ConflictError,
  DomainError,
  ValidationError
} from "./chunk-FYHBHHWK.mjs";

// src/data/operations/control/multi-write-operation.ts
var TRANSACT_WRITE_ITEM_LIMIT = 100;
async function executeMultiWrite(params) {
  const { service, triples, token } = params;
  if (triples.length === 0) {
    throw new ValidationError(
      "executeMultiWrite called with zero triples; at least one triple is required"
    );
  }
  if (triples.length > TRANSACT_WRITE_ITEM_LIMIT) {
    throw new ValidationError(
      `executeMultiWrite received ${triples.length} triples; DynamoDB TransactWriteItems is limited to ${TRANSACT_WRITE_ITEM_LIMIT} items per call`,
      {
        details: {
          itemsRequested: triples.length,
          limit: TRANSACT_WRITE_ITEM_LIMIT
        }
      }
    );
  }
  for (const [index, triple] of triples.entries()) {
    if (!triple || typeof triple !== "object") {
      throw new ValidationError(
        `executeMultiWrite triple at index ${index} is not an object`
      );
    }
    if (typeof triple.entity !== "string" || triple.entity.length === 0) {
      throw new ValidationError(
        `executeMultiWrite triple at index ${index} is missing a non-empty 'entity' key`
      );
    }
    if (!isSupportedAction(triple.action)) {
      throw new ValidationError(
        `executeMultiWrite triple at index ${index} has unsupported action '${String(
          triple.action
        )}'; supported: 'put' | 'create' | 'delete'`
      );
    }
    if (!triple.item || typeof triple.item !== "object") {
      throw new ValidationError(
        `executeMultiWrite triple at index ${index} is missing an 'item' payload`
      );
    }
  }
  let result;
  try {
    result = await service.transaction.write(
      (entities) => triples.map((triple, index) => {
        const transactEntity = entities[triple.entity];
        if (transactEntity === void 0) {
          throw new ValidationError(
            `executeMultiWrite triple at index ${index} references unknown entity '${triple.entity}'; ensure the service exposes it`
          );
        }
        switch (triple.action) {
          case "put":
            return transactEntity.put(triple.item).commit();
          case "create":
            return transactEntity.create(triple.item).commit();
          case "delete":
            return transactEntity.delete(triple.item).commit();
          default:
            throw new ValidationError(
              `executeMultiWrite triple at index ${index} has unsupported action '${String(
                triple.action
              )}'`
            );
        }
      })
    ).go(token === void 0 ? void 0 : { token });
  } catch (err) {
    if (err instanceof DomainError) {
      throw err;
    }
    throw new ConflictError(buildCancellationMessage(err), {
      cause: err,
      details: extractCancellationReasons(err)
    });
  }
  if (result.canceled) {
    throw new ConflictError(
      "TransactWriteItems was canceled by DynamoDB (check CancellationReasons on the cause for details)",
      { details: { canceled: true, data: result.data } }
    );
  }
  return { itemsWritten: triples.length, canceled: false };
}
function isSupportedAction(value) {
  return value === "put" || value === "create" || value === "delete";
}
function buildCancellationMessage(err) {
  if (err instanceof Error && err.message) {
    return `TransactWriteItems failed: ${err.message}`;
  }
  return "TransactWriteItems failed (no error message available)";
}
function extractCancellationReasons(err) {
  if (err && typeof err === "object") {
    const cancellationReasons = err.CancellationReasons;
    if (cancellationReasons !== void 0) {
      return { CancellationReasons: cancellationReasons };
    }
  }
  return void 0;
}

export {
  TRANSACT_WRITE_ITEM_LIMIT,
  executeMultiWrite
};
//# sourceMappingURL=chunk-QJDHVMKT.mjs.map