import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
async function resolveWidgetScope(req, translate, overrides) {
  const auth = await getAuthFromRequest(req);
  if (!auth) {
    throw new CrudHttpError(401, { error: translate("dashboards.errors.unauthorized", "Unauthorized") });
  }
  const container = await createRequestContainer();
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
  const tenantId = overrides?.tenantId ?? auth.tenantId ?? null;
  if (!tenantId) {
    throw new CrudHttpError(400, { error: translate("dashboards.errors.tenant_required", "Tenant context is required") });
  }
  const organizationIds = (() => {
    if (overrides?.organizationId) return [overrides.organizationId];
    if (scope?.selectedId) return [scope.selectedId];
    if (Array.isArray(scope?.filterIds) && scope.filterIds.length > 0) return scope.filterIds;
    if (scope?.allowedIds === null) return null;
    if (auth.orgId) return [auth.orgId];
    return [];
  })();
  if (organizationIds !== null && organizationIds.length === 0) {
    throw new CrudHttpError(400, { error: translate("dashboards.errors.organization_required", "Organization context is required") });
  }
  const em = container.resolve("em");
  return {
    container,
    em,
    tenantId,
    organizationIds
  };
}
export {
  resolveWidgetScope
};
//# sourceMappingURL=widgetScope.js.map
