package com.njcn.rdms.module.system.framework.cache;

import com.njcn.rdms.module.system.dal.redis.RedisKeyConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 系统启动后清理权限相关缓存，避免 SQL 直改后继续命中旧权限数据。
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class PermissionCacheStartupCleaner implements ApplicationRunner {

    private static final List<String> CACHE_NAMES = List.of(
            RedisKeyConstants.ROLE,
            RedisKeyConstants.USER_ROLE_ID_LIST,
            RedisKeyConstants.MENU_ROLE_ID_LIST,
            RedisKeyConstants.PERMISSION_MENU_ID_LIST
    );

    private final CacheManager cacheManager;

    @Override
    public void run(ApplicationArguments args) {
        CACHE_NAMES.forEach(this::clearCacheQuietly);
    }

    private void clearCacheQuietly(String cacheName) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            log.debug("[clearCacheQuietly][cacheName({}) 未注册，跳过清理]", cacheName);
            return;
        }
        cache.clear();
    }

}
