package com.caliverse.admin.global.configuration;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.SslContextFactory;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.security.*;
import java.util.concurrent.TimeoutException;

@Slf4j
@Configuration
public class RabbitMqConfig
{
    @Value("${rabbitmq.url}")
    String m_rabbitmq_host;
    @Value("${rabbitmq.port}")
    int m_rabbitmq_port;
    @Value("${rabbitmq.username}")
    String m_rabbitmq_username;
    @Value("${rabbitmq.password}")
    String m_rabbitmq_password;
    @Value("${rabbitmq.ssl}")
    boolean m_rabbitmq_ssl;

    @Bean
    public Connection rabbitMqClient() throws IOException, TimeoutException, NoSuchAlgorithmException, KeyManagementException {
        var factory = new ConnectionFactory();
        setConnectionInfo(factory);

        if(m_rabbitmq_ssl)
        {
            // SSLContext 초기화
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            // 기본 TrustManager 로드
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            try{
                tmf.init((KeyStore) null);  // 기본 Trust Store로 초기화
            }
            catch(KeyStoreException e){
                log.error(e.getMessage());
                return null;
            }
            // SSLContext를 기본 TrustManager와 SecureRandom으로 초기화
            sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
            // SSLContext를 사용하도록 ConnectionFactory 설정
            factory.useSslProtocol(sslContext);
        }

        return factory.newConnection();
    }

    private void setConnectionInfo(ConnectionFactory factory){
        factory.setHost(m_rabbitmq_host);
        factory.setPort(m_rabbitmq_port);
        factory.setUsername(m_rabbitmq_username);
        factory.setPassword(m_rabbitmq_password);
        factory.setAutomaticRecoveryEnabled(true);
        factory.setRequestedHeartbeat(60);

    }
}
