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 resolveAuthActorId(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 resolveCustomersRequestContext(request) {
  const container = await createRequestContainer();
  const auth = await getAuthFromRequest(request);
  if (!auth || !auth.tenantId) {
    throw new CrudHttpError(401, { error: "Unauthorized" });
  }
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request });
  const selectedOrganizationId = scope?.selectedId ?? auth.orgId ?? null;
  const organizationIds = scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null);
  return {
    container,
    auth,
    em: container.resolve("em").fork(),
    scope,
    selectedOrganizationId,
    organizationIds,
    commandContext: {
      container,
      auth,
      organizationScope: scope,
      selectedOrganizationId,
      organizationIds,
      request
    }
  };
}
export {
  resolveAuthActorId,
  resolveCustomersRequestContext
};
//# sourceMappingURL=interactionRequestContext.js.map
