import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
function resolveTranslationsActorId(auth) {
  if (typeof auth.sub === "string" && auth.sub.trim().length > 0) return auth.sub;
  if (typeof auth.userId === "string" && auth.userId.trim().length > 0) return auth.userId;
  if (typeof auth.keyId === "string" && auth.keyId.trim().length > 0) return auth.keyId;
  return "system";
}
async function resolveTranslationsRouteContext(req) {
  const container = await createRequestContainer();
  const auth = await getAuthFromRequest(req);
  if (!auth || !auth.tenantId) {
    throw new CrudHttpError(401, { error: "Unauthorized" });
  }
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
  const em = container.resolve("em");
  const db = em.getKysely();
  const tenantId = scope?.tenantId ?? auth.tenantId;
  const organizationId = scope?.selectedId ?? auth.orgId ?? null;
  const commandCtx = {
    container,
    auth,
    organizationScope: scope,
    selectedOrganizationId: organizationId,
    organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),
    request: req
  };
  return {
    container,
    auth,
    em,
    db,
    organizationId,
    tenantId,
    commandCtx
  };
}
async function requireTranslationFeatures(context, requiredFeatures) {
  if (!requiredFeatures.length) return;
  const subject = context.auth.sub;
  if (!subject) {
    throw new CrudHttpError(401, { error: "Unauthorized" });
  }
  const rbacService = context.container.resolve("rbacService");
  const hasFeatures = await rbacService.userHasAllFeatures(subject, requiredFeatures, {
    tenantId: context.tenantId,
    organizationId: context.organizationId
  });
  if (!hasFeatures) {
    throw new CrudHttpError(403, { error: "Forbidden" });
  }
}
export {
  requireTranslationFeatures,
  resolveTranslationsActorId,
  resolveTranslationsRouteContext
};
//# sourceMappingURL=context.js.map
