package com.seer.teach.filter.auth;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.seer.teach.config.AuthProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import jakarta.annotation.PreDestroy;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class PermissionCacheManager {

    private final Cache<String, List<Permission>> localCache = CacheBuilder.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(30, TimeUnit.MINUTES)
            .build();

    private  ReactiveRedisTemplate<String, List<Permission>> redisTemplate;
    private  AuthProperties authProperties;

    public PermissionCacheManager(ReactiveRedisTemplate<String, List<Permission>> redisTemplate, AuthProperties authProperties) {
        this.redisTemplate = redisTemplate;
        this.authProperties = authProperties;
    }

    // 获取权限（带缓存策略）
    public Mono<List<Permission>> getPermissions(String key) {
        // 1. 检查本地缓存
        List<Permission> local = localCache.getIfPresent(key);
        if (local != null) {
            return Mono.just(local);
        }

        // 2. 检查Redis缓存
        return redisTemplate.opsForValue().get(key)
                .doOnNext(perms -> {
                    if (perms != null && !perms.isEmpty()) {
                        localCache.put(key, perms);
                    }
                })
                .switchIfEmpty(Mono.defer(() -> {
                    return Mono.empty();
                }));
    }

    public Mono<Void> updateCache(String key, List<Permission> permissions) {
        return Mono.fromRunnable(() -> localCache.put(key, permissions))
                .then(redisTemplate.opsForValue().set(
                        key,
                        permissions,
                        Duration.ofHours(authProperties.getCache().getRedisExpireHours())
                ))
                .then();
    }


    public Mono<Boolean> clearCache(String key) {
        // 1. 清除本地缓存
        localCache.invalidate(key);
        log.info("Cleared cache for key: {}", key);
        // 2. 清除Redis缓存
        return redisTemplate.delete(key)
                .map(count -> count > 0);
    }


    /**
     * 应用关闭前清空所有缓存
     */
    @PreDestroy
    public void clearAllCaches() {
        localCache.asMap().keySet().forEach(key -> {
            redisTemplate.delete(key).subscribe();
        });
        log.info("Cleared all Redis caches based on local cache keys.");

        // 清空本地缓存
        localCache.invalidateAll();
    }
}