package com.bcxin.Infrastructure.messages;

import com.bcxin.Infrastructure.messages.components.DistributedLockProviderImpl;
import com.bcxin.Infrastructure.messages.components.UniqueVerificationCodeGeneratorImpl;
import com.bcxin.Infrastructures.components.LockProvider;
import com.bcxin.Infrastructures.components.RetryProvider;
import com.bcxin.Infrastructures.components.UniqueVerificationCodeGenerator;
import lombok.Data;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
@ConfigurationProperties(prefix = "spring.redis")
public class MessageConfig {
    private String host;
    private String port;
    private String password;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();

        //可以redisss://用来启动SSL
        singleServerConfig.setAddress(String.format("redis://%s:%s", this.getHost(), this.getPort()));
        singleServerConfig.setPassword(this.getPassword());
        singleServerConfig.setConnectionPoolSize(10000);
        singleServerConfig.setPingConnectionInterval(10000);

        RedissonClient redissonClient = Redisson.create(config);

        return redissonClient;
    }

    @Bean
    public LockProvider lockProvider(RedissonClient redissonClient) {
        return new DistributedLockProviderImpl(redissonClient);
    }

    @Bean
    public RetryProvider retryProvider(){
        return new RetryProvider.RetryProviderImpl();
    }

    @Bean
    public UniqueVerificationCodeGenerator uniqueVerificationCodeGenerator(RedissonClient redissonClient,
                                                                           RetryProvider retryProvider) {
        return new UniqueVerificationCodeGeneratorImpl(redissonClient, retryProvider);
    }
}
