package com.caliverse.admin.mongodb.service;

import com.caliverse.admin.domain.entity.log.LogAction;
import com.caliverse.admin.domain.entity.log.LogCategory;
import com.caliverse.admin.domain.request.HistoryRequest;
import com.caliverse.admin.global.common.constants.AdminConstants;
import com.caliverse.admin.mongodb.entity.DBType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Service
@Slf4j
public class OldHistoryLogService {
    @Autowired
    @Qualifier("mongoIndicatorTemplate")
    private MongoTemplate mongoTemplate;

    public <T> List<T> loadHistoryData(DBType dbType, Class<T> class1) {
        List<AggregationOperation> operations = new ArrayList<>();

        operations.add(context ->
                new Document("$match",
                        new Document("dbType", dbType.toString())
                )
        );

        operations.add(context ->
                new Document("$sort",
                        new Document(AdminConstants.MONGO_DB_KEY_TIMESTAMP, -1)
                )
        );

        Aggregation aggregation = Aggregation.newAggregation(operations);
        log.info("loadHistoryData Query: {}", aggregation);

        AggregationResults<T> results = mongoTemplate.aggregate(aggregation, AdminConstants.MONGO_DB_COLLECTION_HISTORY_LOG, class1);
        return results.getMappedResults();
    }
}
