package cn.novalon.gym.manage.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * Redis 工具类（响应式版本）
 * 
 * @author liwentao
 * @date 2026/5/15
 */
@Component
public class RedisUtil {

    @Autowired
    private ReactiveRedisTemplate<String, Object> reactiveRedisTemplate;

    /**
     * 设置值
     */
    public Mono<Boolean> set(String key, Object value) {
        return reactiveRedisTemplate.opsForValue().set(key, value);
    }

    /**
     * 设置值并指定过期时间（秒）
     */
    public Mono<Boolean> setWithExpire(String key, Object value, long timeoutSeconds) {
        return reactiveRedisTemplate.opsForValue().set(key, value, Duration.ofSeconds(timeoutSeconds));
    }

    /**
     * 获取值
     */
    @SuppressWarnings("unchecked")
    public <T> Mono<T> get(String key, Class<T> clazz) {
        return reactiveRedisTemplate.opsForValue().get(key)
                .map(obj -> clazz.isInstance(obj) ? (T) obj : null);
    }

    /**
     * 获取值（返回 Object）
     */
    public Mono<Object> get(String key) {
        return reactiveRedisTemplate.opsForValue().get(key);
    }

    /**
     * 删除key
     */
    public Mono<Long> delete(String key) {
        return reactiveRedisTemplate.delete(key);
    }

    /**
     * 判断key是否存在
     */
    public Mono<Boolean> hasKey(String key) {
        return reactiveRedisTemplate.hasKey(key);
    }

    /**
     * 设置过期时间（秒）
     */
    public Mono<Boolean> expire(String key, long timeoutSeconds) {
        return reactiveRedisTemplate.expire(key, Duration.ofSeconds(timeoutSeconds));
    }

    /**
     * 根据通配符模式删除key
     */
    public Mono<Long> deleteByPattern(String pattern) {
        return reactiveRedisTemplate.keys(pattern)
                .flatMap(keys -> reactiveRedisTemplate.delete(keys)).count();
    }
}