package com.config;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import com.common.entity.BlacklistApiProperties;
import javax.net.ssl.SSLContext;

@Configuration
public class RestTemplateConfig {

    @Value("${blacklist.api.url}")
    private String apiUrl;

    @Value("${blacklist.api.username}")
    private String username;

    @Value("${blacklist.api.password}")
    private String password;

    @Bean
    public RestTemplate restTemplate() throws Exception {
        // 忽略 SSL 证书验证（仅用于内网/测试环境，生产环境建议使用真实证书）
        SSLContext sslContext = SSLContextBuilder.create()
                .loadTrustMaterial((chain, authType) -> true)
                .build();

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
                sslContext, NoopHostnameVerifier.INSTANCE);

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(socketFactory)
                .build();

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        return new RestTemplate(factory);
    }

    @Bean
    public BlacklistApiProperties blacklistApiProperties() {
        return new BlacklistApiProperties(apiUrl, username, password);
    }
}