package com.lesingle.creation.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redis 限流工具类
 * <p>
 * 基于滑动窗口算法实现限流
 *
 * @author lesingle
 * @since 1.0.0
 */
@Slf4j
@Component
public class RateLimiterUtil {

    private static RedisTemplate<String, Object> redisTemplate;

    public RateLimiterUtil(RedisTemplate<String, Object> redisTemplate) {
        RateLimiterUtil.redisTemplate = redisTemplate;
    }

    /**
     * 判断是否允许请求通过
     *
     * @param key     限流 key
     * @param time    时间窗口（秒）
     * @param count   时间窗口内最大请求数
     * @return true-允许通过，false-拒绝请求
     */
    public static boolean tryAcquire(String key, int time, int count) {
        try {
            Long currentCount = redisTemplate.opsForValue().increment(key);
            if (currentCount == 1) {
                // 第一次请求，设置过期时间
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return currentCount <= count;
        } catch (Exception e) {
            log.error("Redis 限流异常，key: {}", key, e);
            // Redis 异常时放行
            return true;
        }
    }

    /**
     * 获取当前请求数
     *
     * @param key 限流 key
     * @return 当前请求数
     */
    public static Long getCurrentCount(String key) {
        try {
            String value = (String) redisTemplate.opsForValue().get(key);
            return value != null ? Long.parseLong(value) : 0L;
        } catch (Exception e) {
            log.error("获取限流计数异常，key: {}", key, e);
            return 0L;
        }
    }

}
