import {
  bridgeLegacyGuard,
  runMutationGuards
} from "./mutation-guard-registry.js";
import { getAllMutationGuardInstances } from "./mutation-guard-store.js";
import { createLogger } from "../logger/index.js";
const logger = createLogger("shared").child({ component: "crud" });
function toRegistryMutationOperation(operation) {
  if (operation === "create" || operation === "delete") return operation;
  return "update";
}
async function resolveRouteUserFeatures(container, auth) {
  if (auth.userFeatures) return auth.userFeatures;
  try {
    const rbac = container.resolve("rbacService");
    if (rbac?.getGrantedFeatures) {
      return await rbac.getGrantedFeatures(auth.userId, {
        tenantId: auth.tenantId,
        organizationId: auth.organizationId ?? null
      });
    }
  } catch {
  }
  return [];
}
async function runRouteMutationGuards(params) {
  const { container, req, auth, input } = params;
  const operation = toRegistryMutationOperation(input.operation);
  const allGuards = [...getAllMutationGuardInstances()];
  const legacyGuard = bridgeLegacyGuard(container);
  if (legacyGuard) allGuards.push(legacyGuard);
  const userFeatures = await resolveRouteUserFeatures(container, auth);
  const guardResult = await runMutationGuards(
    allGuards,
    {
      tenantId: auth.tenantId,
      organizationId: auth.organizationId ?? null,
      userId: auth.userId,
      resourceKind: input.resourceKind,
      resourceId: input.resourceId ?? null,
      operation,
      requestMethod: req.method,
      requestHeaders: req.headers,
      mutationPayload: input.mutationPayload ?? null
    },
    { userFeatures }
  );
  if (!guardResult.ok) {
    const errorStatus = guardResult.errorStatus ?? 422;
    const errorBody = guardResult.errorBody ?? { error: "Operation blocked by guard" };
    return {
      ok: false,
      errorStatus,
      errorBody,
      response: Response.json(errorBody, { status: errorStatus })
    };
  }
  return {
    ok: true,
    modifiedPayload: guardResult.modifiedPayload,
    runAfterSuccess: async () => {
      for (const { guard, metadata } of guardResult.afterSuccessCallbacks) {
        try {
          await guard.afterSuccess({
            tenantId: auth.tenantId,
            organizationId: auth.organizationId ?? null,
            userId: auth.userId,
            resourceKind: input.resourceKind,
            resourceId: input.resourceId ?? "",
            operation,
            requestMethod: req.method,
            requestHeaders: req.headers,
            metadata
          });
        } catch (error) {
          logger.error("Mutation guard afterSuccess failed", { guardId: guard.id, err: error });
        }
      }
    }
  };
}
export {
  runRouteMutationGuards,
  toRegistryMutationOperation
};
//# sourceMappingURL=route-mutation-guard.js.map
