@Nonnull
    @Override
    public CreatedAggregations<AggregationBuilder> doCreateAggregation(Direction direction, String name, Pivot pivot, Time timeSpec, OSGeneratedQueryContext queryContext, Query query) {
        AggregationBuilder root = null;
        AggregationBuilder leaf = null;
        final Interval interval = timeSpec.interval();
        final TimeRange timerange = query.timerange();
        if (interval instanceof AutoInterval autoInterval
                && isAllMessages(timerange)) {
            for (String timeField : timeSpec.fields()) {
                final AutoDateHistogramAggregationBuilder builder = new AutoDateHistogramAggregationBuilder(name)
                        .field(timeField)
                        .setNumBuckets((int) (BASE_NUM_BUCKETS / autoInterval.scaling()))
                        .format(DATE_TIME_FORMAT);

                if (root == null && leaf == null) {
                    root = builder;
                    leaf = builder;
                } else {
                    leaf.subAggregation(builder);
                    leaf = builder;
                }
            }
        } else {
            for (String timeField : timeSpec.fields()) {
                final DateHistogramInterval dateHistogramInterval = new DateHistogramInterval(interval.toDateInterval(query.effectiveTimeRange(pivot)).toString());
                final List<BucketOrder> ordering = orderListForPivot(pivot, queryContext, defaultOrder);
                final DateHistogramAggregationBuilder builder = AggregationBuilders.dateHistogram(name)
                        .field(timeField)
                        .order(ordering)
                        .format(DATE_TIME_FORMAT);

                setInterval(builder, dateHistogramInterval);

                if (root == null && leaf == null) {
                    root = builder;
                    leaf = builder;
                } else {
                    leaf.subAggregation(builder);
                    leaf = builder;
                }
            }
        }

        return CreatedAggregations.create(root, leaf);
    }
@Test
    public void timeSpecIntervalIsCalculatedOnQueryTimeRangeIfNoPivotTimeRange() throws InvalidRangeParametersException {
        final ArgumentCaptor<TimeRange> timeRangeCaptor = ArgumentCaptor.forClass(TimeRange.class);
        when(interval.toDateInterval(timeRangeCaptor.capture())).thenReturn(DateInterval.days(1));
        when(pivot.timerange()).thenReturn(Optional.empty());
        when(query.timerange()).thenReturn(RelativeRange.create(2323));


        this.osTimeHandler.doCreateAggregation(BucketSpecHandler.Direction.Row, "foobar", pivot, time, queryContext, query);
        final TimeRange argumentTimeRange = timeRangeCaptor.getValue();
        assertThat(argumentTimeRange).isEqualTo(RelativeRange.create(2323));
    }