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

/** Мини-клиент RU DATA API: аутентификация и запросы. */
public class RuData {
    private static final String BASE_URL = "https://dh2.efir-net.ru/v2";

    private final HttpClient http = HttpClient.newHttpClient();
    private final String login;
    private final String password;
    private String token;

    public RuData(String login, String password) {
        this.login = login;
        this.password = password;
    }

    public void authenticate() throws Exception {
        String body = "{\"login\": \"" + login + "\", \"password\": \"" + password + "\"}";
        HttpRequest req = HttpRequest.newBuilder()
                .uri(URI.create(BASE_URL + "/Account/Login"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();
        HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString());
        if (resp.statusCode() != 200) {
            throw new RuntimeException("Login failed: HTTP " + resp.statusCode());
        }
        // поле token из JSON-ответа; в реальном проекте используйте Jackson/Gson
        token = resp.body().replaceAll(".*\"token\"\\s*:\\s*\"([^\"]+)\".*", "$1");
    }

    /** POST-запрос с JSON-телом; при 401 — повторный логин и повтор запроса. */
    public String post(String path, String jsonBody) throws Exception {
        if (token == null) {
            authenticate();
        }
        HttpResponse<String> resp = send(path, jsonBody);
        if (resp.statusCode() == 401) {   // токен истёк
            authenticate();
            resp = send(path, jsonBody);
        }
        if (resp.statusCode() != 200) {
            throw new RuntimeException(path + ": HTTP " + resp.statusCode() + " " + resp.body());
        }
        return resp.body();
    }

    private HttpResponse<String> send(String path, String jsonBody) throws Exception {
        HttpRequest req = HttpRequest.newBuilder()
                .uri(URI.create(BASE_URL + path))
                .header("Authorization", "Bearer " + token)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();
        return http.send(req, HttpResponse.BodyHandlers.ofString());
    }
}
