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.Arrays;
import java.util.List;

@Slf4j
@Service
public class BusinessLogUserCreateService extends BusinessLogServiceBase {


    public BusinessLogUserCreateService(@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("$addFields",
                        new Document(AdminConstants.MONGO_DB_KEY_CREATE_TIME,
                                new Document("$let",
                                        new Document("vars",
                                                new Document("found",
                                                        new Document("$regexFind",
                                                                new Document("input", "$message")
                                                                        .append("regex", "\"CreatedTime\":\"([^\"]+)\"")
                                                        )
                                                )
                                        ).append("in",
                                                new Document("$arrayElemAt", Arrays.asList("$$found.captures", 0))
                                        )
                                )
                        )
                )
        );

        operations.add(context ->
                new Document("$group",
                        new Document("_id",
                                new Document(AdminConstants.MONGO_DB_KEY_LOGDAY, "$logDay")
                                        .append(AdminConstants.MONGO_DB_KEY_ACCOUNT_ID, "$accountId")
                                        .append(AdminConstants.MONGO_DB_KEY_TRAN_ID, "$tranId")
                        )
                        .append(AdminConstants.MONGO_DB_KEY_LOGDAY, new Document("$first", "$logDay"))
                        .append(AdminConstants.MONGO_DB_KEY_ACCOUNT_ID, new Document("$first", "$accountId"))
                        .append(AdminConstants.MONGO_DB_KEY_USER_GUID, new Document("$first", "$userGuid"))
                        .append(AdminConstants.MONGO_DB_KEY_USER_NICKNAME, new Document("$max", "$userNickname"))
                        .append(AdminConstants.MONGO_DB_KEY_CREATE_TIME, new Document("$max", "$createdTime"))
                )
        );

        // 최종 출력 형식
        operations.add(context ->
                new Document("$project",
                        new Document("_id", 0)
                                .append(AdminConstants.MONGO_DB_KEY_LOGDAY, "$_id.logDay")
                                .append(AdminConstants.MONGO_DB_KEY_ACCOUNT_ID, "$_id.accountId")
                                .append(AdminConstants.MONGO_DB_KEY_USER_GUID, "$userGuid")
                                .append(AdminConstants.MONGO_DB_KEY_USER_NICKNAME, "$userNickname")
                                .append(AdminConstants.MONGO_DB_KEY_CREATE_TIME, "$createdTime")
                )
        );

        AggregationOptions options = AggregationOptions.builder()
                .allowDiskUse(true)
                .build();
        Aggregation aggregation = Aggregation.newAggregation(operations).withOptions(options);
        log.info("loadBusinessLogData UserCreate 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)
                                )
                );
    }
}
