package top.gtb520.java.pve_back_api;

import org.junit.jupiter.api.Test;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import reactor.netty.http.client.HttpClient;
import reactor.netty.tcp.TcpClient;

public class ResourcesResultTest {
    
    /**
     * 创建忽略SSL证书验证的WebClient实例
     * 用于测试环境或自签名证书场景
     */
    private static WebClient createInsecureWebClient() {
        try {
            // 使用Netty内置的不安全信任管理器工厂
            TcpClient tcpClient = TcpClient.create()
                .secure(sslContextSpec -> {
                    try {
                        sslContextSpec.sslContext(
                            io.netty.handler.ssl.SslContextBuilder.forClient()
                                .trustManager(io.netty.handler.ssl.util.InsecureTrustManagerFactory.INSTANCE)
                                .build()
                        );
                    } catch (Exception e) {
                        throw new RuntimeException("SSL配置失败", e);
                    }
                });
            
            // 创建HttpClient和连接器
            HttpClient httpClient = HttpClient.from(tcpClient);
            ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
            
            // 构建并返回WebClient
            return WebClient.builder()
                .clientConnector(connector)
                .build();
                
        } catch (Exception e) {
            throw new RuntimeException("创建WebClient失败", e);
        }
    }
    
    @Test
    void testHttpsRequest() {
        System.out.println("开始发送HTTPS请求...");
        
        try {
            // 创建忽略证书验证的WebClient
            WebClient client = createInsecureWebClient();
            
            // 发送HTTPS GET请求
            Mono<String> result = client.get()
                .uri("https://10.168.2.2:8013/")
                .retrieve()
                .bodyToMono(String.class);
            
            // 阻塞获取响应结果
            String response = result.block();
            System.out.println("✅ 请求成功!");
            System.out.println("响应内容长度: " + (response != null ? response.length() : 0) + " 字符");
            
            // 如果需要查看完整响应内容，取消下面的注释
            // System.out.println("响应内容: " + response);
            
        } catch (Exception e) {
            System.err.println("❌ HTTPS请求失败: " + e.getMessage());
            System.err.println("可能的原因:");
            System.err.println("1. 目标服务器不可达");
            System.err.println("2. 端口未开放");
            System.err.println("3. 网络连接问题");
            System.err.println("4. SSL配置问题");
            e.printStackTrace();
        }
    }
}