package com.discordrules;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.concurrent.CompletableFuture;

public class DiscordFetcher {
    private static final Logger LOGGER = LoggerFactory.getLogger(DiscordFetcher.class);
    private static final HttpClient CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();

    public static CompletableFuture<String> fetchRulesAsync() {
        if (!ServerRulesConfig.isMessageIdValid()) {
            LOGGER.error("Invalid Discord Message ID in config.");
            return CompletableFuture.completedFuture(null);
        }
        String token = ServerRulesConfig.BOT_TOKEN.get();
        String channelId = ServerRulesConfig.CHANNEL_ID.get();
        String messageId = ServerRulesConfig.MESSAGE_ID.get();
        URI uri = URI.create("https://discord.com/api/v10/channels/" + channelId + "/messages/" + messageId);
        HttpRequest request = HttpRequest.newBuilder().uri(uri)
                .header("Authorization", "Bot " + token)
                .header("Accept", "application/json").GET().build();
        return CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(response -> {
                    if (response.statusCode() == 200) {
                        JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject();
                        return json.get("content").getAsString();
                    } else {
                        LOGGER.error("Discord API returned status: {}", response.statusCode());
                        return null;
                    }
                })
                .exceptionally(ex -> {
                    LOGGER.error("Network error while fetching Discord rules", ex);
                    return null;
                });
    }
}
