package com.arms.api.report.rolling3m.service;

import com.arms.api.issue.almapi.model.entity.AlmIssueEntity;
import com.arms.api.report.rolling3m.assignee.model.dto.Rolling3mDTO;
import com.arms.api.report.rolling3m.model.vo.IssueByTeamVO;
import com.arms.api.report.rolling3m.model.vo.IssueAverageByTeamVO;
import com.arms.egovframework.javaservice.esframework.esquery.SimpleQuery;
import com.arms.egovframework.javaservice.esframework.esquery.filter.RangeQueryFilter;
import com.arms.egovframework.javaservice.esframework.model.dto.esquery.MainGroupDTO;
import com.arms.egovframework.javaservice.esframework.model.dto.esquery.SubGroupFieldDTO;
import com.arms.egovframework.javaservice.esframework.model.dto.request.AggregationRequestDTO;
import com.arms.egovframework.javaservice.esframework.model.vo.DocumentAggregations;
import com.arms.egovframework.javaservice.esframework.repository.common.EsCommonRepositoryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import static com.arms.egovframework.javaservice.esframework.esquery.SimpleQuery.aggregation;

@Service
@RequiredArgsConstructor
public class TeamAverageStatByStateServiceImpl implements TeamAverageStatByStateService {

    private final EsCommonRepositoryWrapper<AlmIssueEntity> esCommonRepositoryWrapper;

    @Override
    public IssueAverageByTeamVO selectTeamAverageStatsByAssignee(Rolling3mDTO rolling3mDTO) {
        return IssueAverageByTeamVO.of(
                mapToIssueByTeamVO(queryByAssignee(rolling3mDTO, null)),
                mapToIssueByTeamVO(queryByAssignee(rolling3mDTO, Boolean.TRUE)),
                mapToIssueByTeamVO(queryByAssignee(rolling3mDTO, Boolean.FALSE))
        );
    }

    private SimpleQuery<MainGroupDTO> queryByAssignee(Rolling3mDTO rolling3mDTO, Boolean isReq) {
        SimpleQuery<MainGroupDTO> query = aggregation(
                AggregationRequestDTO.builder()
                        .mainField("assignee.assignee_accountId.keyword")
                        .build()
        )
                .andTermQueryFilter("pdServiceId", rolling3mDTO.getPdServiceId())
                .andTermsQueryFilter("pdServiceVersions", rolling3mDTO.getPdServiceVersions())
                .andExistsQueryFilter("assignee.assignee_accountId")
                .andRangeQueryFilter(RangeQueryFilter.of("created").betweenDate("now-3M/d", "now"));

        if (isReq != null) {
            query.andTermQueryFilter("isReq", isReq);
        }

        return query;
    }

    private IssueByTeamVO mapToIssueByTeamVO(SimpleQuery<MainGroupDTO> query) {
        DocumentAggregations agg = esCommonRepositoryWrapper.aggregateRecent(query);
        return IssueByTeamVO.builder()
                .totalHits(agg.getTotalHits())
                .assigneeCount(agg.deepestList().size())
                .build();
    }
}
