package com.arms.egovframework.javaservice.esframework.factory.creator;

import com.arms.egovframework.javaservice.esframework.esquery.EsQuery;
import com.arms.egovframework.javaservice.esframework.factory.builder.AggregationQueryBuilder;
import com.arms.egovframework.javaservice.esframework.model.dto.esquery.MainGroupDTO;
import lombok.Getter;
import org.opensearch.search.aggregations.AggregationBuilders;
import org.opensearch.search.aggregations.metrics.ValueCountAggregationBuilder;

import java.util.Optional;

@Getter
public class AggregationQueryCountCreator extends AggregationQueryBuilder<ValueCountAggregationBuilder> {

    private AggregationQueryCountCreator(MainGroupDTO mainGroupDTO, EsQuery esQuery){
        super(
            mainGroupDTO
            ,esQuery
            ,AggregationBuilders
                .count(Optional.ofNullable(mainGroupDTO.getMainFieldAlias()).orElseGet(() -> "group_by_" + mainGroupDTO.getMainField()))
                .field(mainGroupDTO.getMainField())
        );
    }

    public static AggregationQueryCountCreator of(EsQuery esQuery){
        return new AggregationQueryCountCreator(new MainGroupDTO(),esQuery);
    }

    public static AggregationQueryCountCreator of(MainGroupDTO mainGroupDTO, EsQuery esQuery){
        return new AggregationQueryCountCreator(mainGroupDTO,esQuery);
    }

}
