package org.lingniu.sdk.utils;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

public class HttpClientUtils {
    
    private static final HttpClient DEFAULT_CLIENT = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .version(HttpClient.Version.HTTP_2)
            .build();
    
    // GET请求
    public static String get(String url, Map<String, String> headers) throws Exception {
        HttpRequest.Builder builder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET();
        
        if (headers != null) {
            headers.forEach(builder::header);
        }
        
        HttpRequest request = builder.build();
        
        HttpResponse<String> response = DEFAULT_CLIENT.send(
                request, 
                HttpResponse.BodyHandlers.ofString()
        );
        
        if (response.statusCode() >= 200 && response.statusCode() < 300) {
            return response.body();
        } else {
            throw new RuntimeException("HTTP Error: " + response.statusCode());
        }
    }
    
    // POST请求
    public static String post(String url, String body, Map<String, String> headers)
            throws Exception {
        HttpRequest.Builder builder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .POST(HttpRequest.BodyPublishers.ofString(body));
        
        if (headers != null) {
            headers.forEach(builder::header);
        }
        
        HttpRequest request = builder.build();
        
        HttpResponse<String> response = DEFAULT_CLIENT.send(
                request, 
                HttpResponse.BodyHandlers.ofString()
        );
        
        if (response.statusCode() >= 200 && response.statusCode() < 300) {
            return response.body();
        } else {
            throw new RuntimeException("HTTP Error: " + response.statusCode());
        }
    }
    
    // POST JSON请求
    public static String postJson(String url, String json) throws Exception {
        return post(url, json, Map.of(
            "Content-Type", "application/json",
            "Accept", "application/json"
        ));
    }
    
    // 异步GET请求
    public static CompletableFuture<String> getAsync(String url) {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET()
                .build();
        
        return DEFAULT_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(response -> {
                    if (response.statusCode() >= 200 && response.statusCode() < 300) {
                        return response.body();
                    } else {
                        throw new RuntimeException("HTTP Error: " + response.statusCode());
                    }
                });
    }
    
    // 测试示例
    public static void main(String[] args) {
        try {
            // 同步GET
            String response = get(
                "https://jsonplaceholder.typicode.com/posts/1", 
                Map.of("User-Agent", "Java Client")
            );
            System.out.println("GET Response: " + response);
            
            // 异步GET
            getAsync("https://jsonplaceholder.typicode.com/posts/2")
                .thenAccept(r -> System.out.println("Async Response: " + r))
                .join();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}