import {
  getDynamoControlService
} from "./chunk-EUIP2U5F.mjs";

// src/data/operations/control/counters/counter-apply-operation.ts
var COUNTER_TARGET = {
  Tenant: "Tenant",
  Workspace: "Workspace",
  User: "User"
};
async function applyCounterDeltaOperation(params) {
  const { mutation, tableName } = params;
  const service = getDynamoControlService(tableName);
  const patch = buildPatch(service, mutation);
  try {
    if (mutation.delta > 0) {
      await patch.add({ [mutation.attribute]: mutation.delta }).go();
      return true;
    }
    await patch.add({ [mutation.attribute]: mutation.delta }).where((attr, { gt }) => gt(attr[mutation.attribute], 0)).go();
    return true;
  } catch (err) {
    if (isConditionalCheckFailure(err)) {
      return false;
    }
    throw err;
  }
}
function buildPatch(service, mutation) {
  switch (mutation.target) {
    case COUNTER_TARGET.Tenant:
      return service.entities.tenant.patch({
        tenantId: mutation.tenantId,
        sk: "CURRENT"
      });
    case COUNTER_TARGET.Workspace:
      return service.entities.workspace.patch({
        tenantId: mutation.tenantId,
        id: mutation.workspaceId,
        sk: "CURRENT"
      });
    case COUNTER_TARGET.User:
      return service.entities.user.patch({
        id: mutation.userId,
        sk: "CURRENT"
      });
  }
}
function isConditionalCheckFailure(err) {
  if (typeof err !== "object" || err === null) {
    return false;
  }
  const e = err;
  if (e.name === "ConditionalCheckFailedException" || e.code === "ConditionalCheckFailedException" || e.cause?.name === "ConditionalCheckFailedException") {
    return true;
  }
  return typeof e.message === "string" ? e.message.includes("ConditionalCheckFailed") : false;
}

// src/data/operations/control/counters/role-admin-classification.ts
function isAdminRoleAssignment(input) {
  if (codeIsAdminTier(input.roleLevel)) {
    return true;
  }
  if (idMatchesAdmin(input.roleId)) {
    return true;
  }
  return false;
}
function codeIsAdminTier(roleLevel) {
  if (typeof roleLevel !== "string" || roleLevel.length === 0) {
    return false;
  }
  const lower = roleLevel.toLowerCase();
  return lower === "admin" || lower.endsWith("admin");
}
function idMatchesAdmin(roleId) {
  if (typeof roleId !== "string" || roleId.length === 0) {
    return false;
  }
  return roleId.toLowerCase().includes("admin");
}

export {
  COUNTER_TARGET,
  applyCounterDeltaOperation,
  isAdminRoleAssignment
};
//# sourceMappingURL=chunk-RQKJNMX5.mjs.map