package com.seer.teach.filter.auth.redis;

import com.seer.teach.filter.auth.PermissionCacheManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.connection.ReactiveSubscription;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.ReactiveRedisMessageListenerContainer;

@Configuration
@Slf4j
public class RedisSubConfig {

    public static final String CACHE_CLEAR_CHANNEL = "cache_clear_channel";

    @Autowired
    private PermissionCacheManager cacheManagerService;

    @ConditionalOnBean(ReactiveRedisConnectionFactory.class)
    @Bean
    public ReactiveRedisMessageListenerContainer reactiveRedisMessageListenerContainer(
            ReactiveRedisConnectionFactory factory) {
        ReactiveRedisMessageListenerContainer container = new ReactiveRedisMessageListenerContainer(factory);
        try {
            container.receive(ChannelTopic.of(CACHE_CLEAR_CHANNEL))
                    .map(ReactiveSubscription.Message::getMessage)
                    .subscribe(
                            message -> {
                                try {
                                    cacheManagerService.clearCache(message);
                                } catch (Exception e) {
                                    log.error("Error processing Redis message", e);
                                }
                            },
                            throwable -> log.error("Redis message listener error", throwable)
                    );
        } catch (Exception e) {
            log.warn("Failed to set up Redis message listener, may be due to Redis connection issue: {}", e.getMessage());
        }
        return container;
    }
}