import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { ensureOrganizationScope, ensureTenantScope } from "@open-mercato/shared/lib/commands/scope";
import { extractUndoPayload } from "@open-mercato/shared/lib/commands/undo";
import { normalizeAuthorUserId } from "@open-mercato/shared/lib/commands/helpers";
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { User } from "@open-mercato/core/modules/auth/data/entities";
import { ResourcesResource } from "../data/entities.js";
async function requireResource(em, resourceId, message = "Resource not found") {
  const resource = await em.findOne(ResourcesResource, { id: resourceId });
  if (!resource) throw new CrudHttpError(404, { error: message });
  return resource;
}
async function resolveResourceAuthorUserId(em, explicitAuthorUserId, ctx, scope) {
  const normalizedAuthor = normalizeAuthorUserId(explicitAuthorUserId, ctx.auth);
  const fallbackAuthor = normalizeAuthorUserId(null, ctx.auth);
  const isExplicitSuperAdminAuthor = Boolean(explicitAuthorUserId) && normalizedAuthor === explicitAuthorUserId && ctx.auth?.isApiKey !== true && ctx.auth?.isSuperAdmin === true;
  if (!isExplicitSuperAdminAuthor || !normalizedAuthor) return normalizedAuthor;
  const author = await findOneWithDecryption(
    em,
    User,
    {
      id: normalizedAuthor,
      tenantId: scope.tenantId,
      organizationId: scope.organizationId,
      deletedAt: null
    },
    void 0,
    { tenantId: scope.tenantId, organizationId: scope.organizationId }
  );
  return author ? normalizedAuthor : fallbackAuthor;
}
export {
  ensureOrganizationScope,
  ensureTenantScope,
  extractUndoPayload,
  requireResource,
  resolveResourceAuthorUserId
};
//# sourceMappingURL=shared.js.map
