package com.kexue.skills.common.util;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

/**
 * HTTP工具类
 *
 * @author 维哥
 * @since 2026-01-28
 */
public class HttpUtil {

    /**
     * 发送POST请求到指定URL（通用HTTP客户端方法，使用JDK自带HttpClient）
     *
     * @param url         请求URL
     * @param requestBody 请求体对象
     * @param apiKey      API密钥
     * @param authHeader  认证头
     * @return 响应结果
     * @throws Exception 异常信息
     */
    public static String sendPostRequest(String url, Object requestBody, String apiKey, String authHeader) throws Exception {
        // 创建HttpClient实例
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(30))
                .build();
        
        // 构建请求体
        String jsonInputString = JSON.toJSONString(requestBody);
        
        // 构建HttpRequest
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonInputString, StandardCharsets.UTF_8));
        
        // 设置认证头
        if (authHeader != null) {
            requestBuilder.header("Authorization", authHeader);
        } else if (apiKey != null) {
            requestBuilder.header("Authorization", "Bearer " + apiKey);
        }
        
        // 发送请求并获取响应
        HttpResponse<String> response = client.send(requestBuilder.build(), HttpResponse.BodyHandlers.ofString());
        
        return response.body();
    }

    /**
     * 发送 POST 请求到指定 URL
     *
     * @param url         请求 URL
     * @param requestBody 请求体字符串
     * @return 响应结果
     * @throws Exception 异常信息
     */
    public static String post(String url, String requestBody) throws Exception {
        // 创建 HttpClient 实例
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(30))
                .build();
            
        return postWithClient(url, requestBody, client);
    }
        
    /**
     * 发送 POST 请求到指定 URL（使用指定的 HttpClient，支持连接复用）
     *
     * @param url         请求 URL
     * @param requestBody 请求体字符串
     * @param client      HttpClient 实例
     * @return 响应结果
     * @throws Exception 异常信息
     */
    public static String postWithClient(String url, String requestBody, HttpClient client) throws Exception {
        // 构建 HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/xml")
                .header("Accept", "application/xml")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody, StandardCharsets.UTF_8))
                .build();
            
        // 发送请求并获取响应
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        
        // 打印响应状态码和响应体
        System.out.println("HTTP 状态码: " + response.statusCode());
        System.out.println("响应体: " + response.body());
            
        return response.body();
    }
}