package com.red.circle.other.infra.database.mongo.service.ranking;

import com.red.circle.other.infra.database.mongo.entity.ranking.RankingRewardSnapshot;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import lombok.RequiredArgsConstructor;

/**
 * 排名奖励快照服务.
 */
@Service
@RequiredArgsConstructor
public class RankingRewardSnapshotService {

    private final MongoTemplate mongoTemplate;

    /**
     * 保存快照.
     */
    public void save(RankingRewardSnapshot snapshot) {
        mongoTemplate.save(snapshot);
    }

    /**
     * 获取最新快照.
     */
    public RankingRewardSnapshot getLatestSnapshot(String activityType, String origin, String cycleKey) {
        Query query = new Query();
        query.addCriteria(Criteria.where("activityType").is(activityType)
            .and("origin").is(origin)
            .and("cycleKey").is(cycleKey));
        query.with(org.springframework.data.domain.Sort.by(
            org.springframework.data.domain.Sort.Direction.DESC, "snapshotTime"));
        query.limit(1);
        
        return mongoTemplate.findOne(query, RankingRewardSnapshot.class);
    }

    /**
     * 删除旧快照.
     */
    public void deleteOldSnapshots(String activityType, String origin, String cycleKey) {
        Query query = new Query();
        query.addCriteria(Criteria.where("activityType").is(activityType)
            .and("origin").is(origin)
            .and("cycleKey").is(cycleKey));
        
        mongoTemplate.remove(query, RankingRewardSnapshot.class);
    }
}
