package com.smqjh.agent.mcp;

import com.fasterxml.jackson.databind.node.ObjectNode;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

final class SmqjhCloudClient {
    private final AppConfig config;
    private final HttpClient httpClient;

    SmqjhCloudClient(AppConfig config) {
        this.config = config;
        this.httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofMillis(config.requestTimeoutMs))
            .build();
    }

    ObjectNode health() throws Exception {
        URI uri = URI.create(config.baseUrl + "/smqjh-auth/api/v1/auth/captcha");
        HttpRequest request = HttpRequest.newBuilder(uri)
            .timeout(Duration.ofMillis(config.requestTimeoutMs))
            .header("Accept", "application/json")
            .GET()
            .build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        ObjectNode result = Jsons.object();
        result.put("ok", response.statusCode() >= 200 && response.statusCode() < 300);
        result.put("status", response.statusCode());
        result.put("url", uri.toString());
        result.put("bodyPreview", response.body() == null ? "" : response.body().substring(0, Math.min(500, response.body().length())));
        return result;
    }
}
