package kr.co.accura.wbx.spring.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

/**
 * Redis/인메모리 캐시 자동 구성.
 *
 * 동작 방식:
 *   1. Redis 연결 가능 → RedisCacheManager 사용
 *   2. Redis 연결 불가 → ConcurrentMapCacheManager 자동 전환 (인메모리)
 *
 * 개발 PC에서 Docker/Redis 없이도 애플리케이션이 정상 구동됩니다.
 */
@Configuration
@AutoConfigureBefore(CacheAutoConfiguration.class)
public class RedisCacheAutoConfig {

    private static final Logger log = LoggerFactory.getLogger(RedisCacheAutoConfig.class);

    @Bean
    @Primary
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        try {
            redisConnectionFactory.getConnection().close();
            log.info("[WBX] Redis 캐시 사용 (연결 성공)");
            return RedisCacheManager.builder(redisConnectionFactory).build();
        } catch (Exception e) {
            log.warn("[WBX] Redis 연결 실패 — 인메모리 캐시로 전환 ({})", e.getMessage());
            return new ConcurrentMapCacheManager("permissions", "deptScopes");
        }
    }
}
