import {
  COUNTER_MAINTENANCE_CONSUMER_NAME,
  import_workflows
} from "./chunk-LKKLO66E.mjs";
import {
  COUNTER_TARGET,
  applyCounterDeltaOperation,
  isAdminRoleAssignment
} from "./chunk-RQKJNMX5.mjs";
import "./chunk-EUIP2U5F.mjs";
import "./chunk-TRY7JGWO.mjs";
import {
  require_lib
} from "./chunk-KMEWULMX.mjs";
import {
  __toESM
} from "./chunk-LZOMFHX3.mjs";

// src/workflows/control-plane/counter-maintenance/counter-maintenance.handler.ts
var import_workflows2 = __toESM(require_lib());
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

// src/data/operations/control/counters/counter-event-router.ts
function membershipMutations(payload, delta) {
  const mutations = [];
  if (payload.workspaceId !== void 0) {
    mutations.push({
      target: COUNTER_TARGET.Workspace,
      tenantId: payload.tenantId,
      workspaceId: payload.workspaceId,
      attribute: "usersInWorkspace",
      delta
    });
    if (payload.userId !== void 0) {
      mutations.push({
        target: COUNTER_TARGET.User,
        userId: payload.userId,
        attribute: "workspacesForUser",
        delta
      });
    }
    return mutations;
  }
  mutations.push({
    target: COUNTER_TARGET.Tenant,
    tenantId: payload.tenantId,
    attribute: "usersInTenant",
    delta
  });
  if (payload.userId !== void 0) {
    mutations.push({
      target: COUNTER_TARGET.User,
      userId: payload.userId,
      attribute: "tenantsForUser",
      delta
    });
  }
  return mutations;
}
function roleAssignmentMutations(payload, delta) {
  if (payload.workspaceId === void 0) {
    return [];
  }
  const attribute = isAdminRoleAssignment({
    roleLevel: payload.roleLevel,
    roleId: payload.roleId
  }) ? "adminUsersInWorkspace" : "normalUsersInWorkspace";
  return [
    {
      target: COUNTER_TARGET.Workspace,
      tenantId: payload.tenantId,
      workspaceId: payload.workspaceId,
      attribute,
      delta
    }
  ];
}
function workspaceMutations(payload, delta) {
  return [
    {
      target: COUNTER_TARGET.Tenant,
      tenantId: payload.tenantId,
      attribute: "workspacesInTenant",
      delta
    }
  ];
}

// src/workflows/control-plane/counter-maintenance/counter-maintenance.handler.ts
var errorMessage = (err) => err instanceof Error ? err.message : String(err);
function resolveEvent(event) {
  const detailType = event["detail-type"];
  switch (detailType) {
    case import_workflows.ControlPlaneMembershipCreatedV1.detailType:
      return resolveMembership(event, import_workflows.ControlPlaneMembershipCreatedV1, 1);
    case import_workflows.ControlPlaneMembershipDeletedV1.detailType:
      return resolveMembership(event, import_workflows.ControlPlaneMembershipDeletedV1, -1);
    case import_workflows.ControlPlaneRoleAssignmentCreatedV1.detailType:
      return resolveRoleAssignment(
        event,
        import_workflows.ControlPlaneRoleAssignmentCreatedV1,
        1
      );
    case import_workflows.ControlPlaneRoleAssignmentDeletedV1.detailType:
      return resolveRoleAssignment(
        event,
        import_workflows.ControlPlaneRoleAssignmentDeletedV1,
        -1
      );
    case import_workflows.ControlPlaneWorkspaceCreatedV1.detailType:
      return resolveWorkspace(event, import_workflows.ControlPlaneWorkspaceCreatedV1, 1);
    case import_workflows.ControlPlaneWorkspaceDeletedV1.detailType:
      return resolveWorkspace(event, import_workflows.ControlPlaneWorkspaceDeletedV1, -1);
    default:
      return null;
  }
}
function resolveMembership(event, entry, delta) {
  const parsed = (0, import_workflows2.parseWorkflowEvent)(event, entry);
  return {
    mutations: membershipMutations(parsed.envelope.payload, delta),
    dedupKey: parsed.dedupKey
  };
}
function resolveRoleAssignment(event, entry, delta) {
  const parsed = (0, import_workflows2.parseWorkflowEvent)(event, entry);
  return {
    mutations: roleAssignmentMutations(parsed.envelope.payload, delta),
    dedupKey: parsed.dedupKey
  };
}
function resolveWorkspace(event, entry, delta) {
  const parsed = (0, import_workflows2.parseWorkflowEvent)(event, entry);
  return {
    mutations: workspaceMutations(parsed.envelope.payload, delta),
    dedupKey: parsed.dedupKey
  };
}
var runCounterMaintenance = async (event, deps) => {
  const resolved = resolveEvent(event);
  if (resolved === null) {
    return;
  }
  const recordResult = await deps.dedupClient.recordIfAbsent({
    consumerName: COUNTER_MAINTENANCE_CONSUMER_NAME,
    eventId: resolved.dedupKey.eventId,
    attempt: resolved.dedupKey.attempt
  });
  if (!recordResult.recorded) {
    return;
  }
  try {
    for (const mutation of resolved.mutations) {
      await deps.applyMutation(mutation);
    }
  } catch (err) {
    await deps.dedupClient.markFailed({
      consumerName: COUNTER_MAINTENANCE_CONSUMER_NAME,
      eventId: resolved.dedupKey.eventId,
      attempt: resolved.dedupKey.attempt,
      reason: errorMessage(err)
    });
    throw err;
  }
};
var productionDependencies = () => {
  const dynamodb = new DynamoDBClient({});
  return {
    dedupClient: (0, import_workflows2.workflowDedupClient)(dynamodb),
    applyMutation: async (mutation) => {
      await applyCounterDeltaOperation({ mutation });
    }
  };
};
var handler = async (event) => runCounterMaintenance(event, productionDependencies());
export {
  handler,
  runCounterMaintenance
};
//# sourceMappingURL=counter-maintenance.handler.mjs.map