package com.caliverse.admin.logs.logservice.businesslogservice;

import com.caliverse.admin.global.common.constants.AdminConstants;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class BusinessLogNruService extends BusinessLogServiceBase {


    public BusinessLogNruService(@Qualifier("mongoBusinessLogTemplate") MongoTemplate mongoTemplate) {
        super(mongoTemplate);
    }


    public <T> List<T> loadBusinessLogData(String startTime, String endTime, Class<T> class1) {

        Criteria criteria = makeCriteria(startTime, endTime);
        List<AggregationOperation> operations = setDefaultOperation(criteria);

        operations.add(context ->
                new Document("$group",
                        new Document("_id",
                                new Document("logDay", "$logDay")
                                        .append("tranId", "$tranId")
                        )
                                .append("logDay",
                                        new Document("$first", "$logDay")
                                )
                )
        );

        // logDay별 카운트 집계
        operations.add(context ->
                new Document("$group",
                        new Document("_id", "$_id.logDay")
                                .append("nru",
                                        new Document("$sum", 1)
                                )
                )
        );

        // 최종 출력 형식
        operations.add(context ->
                new Document("$project",
                        new Document("_id", 0)
                                .append("logDay", "$_id")
                                .append("nru", 1)
                )
        );

        Aggregation aggregation = Aggregation.newAggregation(operations);
        log.info("loadBusinessLogData CharacterCreate Query: {}", aggregation);
        AggregationResults<T> results = getMongoTemplate().aggregate(aggregation, AdminConstants.MONGO_DB_COLLECTION_LOG, class1);

        return results.getMappedResults();
    }

    protected Criteria makeCriteria(String startTime, String endTime) {
        return new Criteria()
                .andOperator(
                        Criteria.where(AdminConstants.MONGO_DB_KEY_LOGTIME).gte(startTime)
                        ,Criteria.where(AdminConstants.MONGO_DB_KEY_LOGTIME).lt(endTime)
                        , new Criteria()
                                .orOperator(
                                        Criteria.where(AdminConstants.MONGO_DB_KEY_MESSAGE).regex(AdminConstants.REGEX_MSG_CHARACTER_CREATE)
                                )
                );
    }
}
