package com.fs.course.utils;

import com.fs.common.constant.VideoCommentKeysConstant;
import com.fs.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * 视频评论数 Redis 索引，避免 KEYS comment:count:video:* 全库扫描。
 */
@Component
public class VideoCommentCountRedisUtil {

    public static final String COUNT_PREFIX = VideoCommentKeysConstant.VIDEO_COMMENT_COUNT_PREFIX;
    public static final String COUNT_INDEX = VideoCommentKeysConstant.VIDEO_COMMENT_COUNT_INDEX;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public static String commentCountKey(Long videoId) {
        return COUNT_PREFIX + videoId;
    }

    public void track(String cacheKey) {
        redisCache.redisTemplate.opsForSet().add(COUNT_INDEX, cacheKey);
    }

    public void track(Long videoId) {
        track(commentCountKey(videoId));
    }

    public void untrack(String cacheKey) {
        redisCache.redisTemplate.opsForSet().remove(COUNT_INDEX, cacheKey);
    }

    public void untrack(Long videoId) {
        untrack(commentCountKey(videoId));
    }

    /**
     * 评论数 +1 并登记索引（写入 Redis 时调用，供定时同步扫索引）
     */
    public void incrementCommentCount(Long videoId) {
        String cacheKey = commentCountKey(videoId);
        redisTemplate.opsForValue().increment(cacheKey, 1);
        track(cacheKey);
    }

    public Set<String> listKeys() {
        Set<Object> members = redisCache.redisTemplate.opsForSet().members(COUNT_INDEX);
        if (members == null || members.isEmpty()) {
            return Collections.emptySet();
        }
        Set<String> result = new HashSet<>(members.size());
        for (Object member : members) {
            String cacheKey = member.toString();
            if (Boolean.TRUE.equals(redisCache.redisTemplate.hasKey(cacheKey))) {
                result.add(cacheKey);
            } else {
                untrack(cacheKey);
            }
        }
        return result;
    }
}
