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.BucketOrder;
import org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder;

import java.util.Optional;

@Getter
public class AggregationQueryCreator extends AggregationQueryBuilder<TermsAggregationBuilder> {

    private AggregationQueryCreator(MainGroupDTO mainGroupDTO, EsQuery esQuery){
        super(
            mainGroupDTO
            ,esQuery
            ,AggregationBuilders
                .terms(Optional.ofNullable(mainGroupDTO.getMainFieldAlias()).orElseGet(() -> "group_by_" + mainGroupDTO.getMainField()))
                .field(mainGroupDTO.getMainField())
                .size(mainGroupDTO.getSize())
                .order(BucketOrder.count(mainGroupDTO.isAscending()))
        );
    }

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

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

}
