package com.firefrostgaming.rules;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CompletableFuture;

public class DiscordFetcher {
    private static final Logger LOGGER = LogManager.getLogger(DiscordFetcher.class);

    public static CompletableFuture<String> fetchRulesAsync() {
        if (!ServerRulesConfig.isMessageIdValid()) {
            LOGGER.error("Invalid Discord Message ID in config.");
            return CompletableFuture.completedFuture(null);
        }
        return CompletableFuture.supplyAsync(() -> {
            try {
                String token = ServerRulesConfig.BOT_TOKEN.get();
                String channelId = ServerRulesConfig.CHANNEL_ID.get();
                String messageId = ServerRulesConfig.MESSAGE_ID.get();
                URL url = new URL("https://discord.com/api/v10/channels/" + channelId + "/messages/" + messageId);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setRequestProperty("Authorization", "Bot " + token);
                con.setRequestProperty("Accept", "application/json");
                con.setConnectTimeout(10000);
                con.setReadTimeout(10000);
                int status = con.getResponseCode();
                if (status == 200) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    StringBuilder content = new StringBuilder();
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) { content.append(inputLine); }
                    in.close();
                    JsonObject json = new JsonParser().parse(content.toString()).getAsJsonObject();
                    return json.get("content").getAsString();
                } else {
                    LOGGER.error("Discord API returned status: {}", status);
                    return null;
                }
            } catch (Exception ex) {
                LOGGER.error("Network error while fetching Discord rules", ex);
                return null;
            }
        });
    }
}
