package com.cf.imes.framework.redis.config;

import cn.hutool.core.bean.BeanUtil;
import com.cf.imes.framework.common.util.encrypt.AesUtils;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.redisson.config.SingleServerConfig;
import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

/**
 * @author Gqr
 * @since 2024/8/27 9:46
 */
@AutoConfiguration
@ConditionalOnProperty(name = "chenfeng.encrypt.enable", havingValue = "true")
public class ChenfengRedisEncryptAutoConfiguration {

    @Value("${chenfeng.encrypt.publicKey:}")
    private String publicKey;

    @Bean
    public RedissonAutoConfigurationCustomizer redissonAutoConfigurationCustomizer() {
        return configuration -> {
            Config redissonConfig = new Config();
            BeanUtil.copyProperties(configuration, redissonConfig);

            String password;

            // 单机模式
            if (redissonConfig.isSingleConfig()) {
                SingleServerConfig singleServerConfig = redissonConfig.useSingleServer();
                password = singleServerConfig.getPassword();
                singleServerConfig.setPassword(
                        StringUtils.isEmpty(password) ? null : AesUtils.decrypt(password, publicKey));
                return;
            }

            // 哨兵模式
            if (redissonConfig.isSentinelConfig()) {
                SentinelServersConfig sentinelServersConfig = redissonConfig.useSentinelServers();
                password = sentinelServersConfig.getPassword();
                sentinelServersConfig.setPassword(
                        StringUtils.isEmpty(password) ? null : AesUtils.decrypt(password, publicKey));
                return;
            }

            // 集群模式
            if (redissonConfig.isClusterConfig()) {
                ClusterServersConfig clusterServersConfig = redissonConfig.useClusterServers();
                password = clusterServersConfig.getPassword();
                clusterServersConfig.setPassword(
                        StringUtils.isEmpty(password) ? null : AesUtils.decrypt(password, publicKey));
            }
        };
    }
}
