package de.winniepat.citrus.managers;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import de.winniepat.citrus.Client;
import de.winniepat.citrus.ModConfig;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ConfigManager {
    private static final Gson GSON = new GsonBuilder()
            .setPrettyPrinting()
            .create();
    private static final File CONFIG_FILE = new File(Client.CONFIG_DIR, "settings.json");

    public static ModConfig config = new ModConfig();

    public static void load() {
        if (!CONFIG_FILE.exists()) {
            Client.debugLog("Config file not found, creating default");
            save();
            return;
        }

        try (FileReader reader = new FileReader(CONFIG_FILE)) {
            config = GSON.fromJson(reader, ModConfig.class);

            if (config.betaConfig == null) {
                config.betaConfig = new ModConfig.BetaConfig();
                Client.debugLog("Initialized new beta config for existing user");
            }

            Client.debugLog("Config loaded successfully");

        } catch (IOException e) {
            Client.logger.error("Error while loading config", e);
            config = new ModConfig();
        }
    }

    public static void save() {
        if (!Client.CONFIG_DIR.exists()) {
            Client.CONFIG_DIR.mkdirs();
        }

        try (FileWriter writer = new FileWriter(CONFIG_FILE)) {
            GSON.toJson(config, writer);
            Client.logger.debug("Config saved successfully");
        } catch (IOException e) {
            Client.logger.error("Error while saving config", e);
        }
    }

    public static ModConfig.BetaConfig getBetaConfig() {
        return config.betaConfig;
    }

    public static void updateBetaConfig(ModConfig.BetaConfig newBetaConfig) {
        config.betaConfig = newBetaConfig;
        save();
    }

    public static void saveBetaToken(String token, long expiresAt) {
        config.betaConfig.verificationToken = token;
        config.betaConfig.tokenExpiresAt = expiresAt;
        save();
    }

    public static boolean hasBetaKey() {
        return config.betaConfig != null &&
                config.betaConfig.betaKey != null &&
                !config.betaConfig.betaKey.trim().isEmpty();
    }

    public static boolean hasValidToken() {
        if (config.betaConfig == null || config.betaConfig.verificationToken == null || config.betaConfig.verificationToken.trim().isEmpty()) {
            return false;
        }

        return System.currentTimeMillis() < (config.betaConfig.tokenExpiresAt - (5 * 60 * 1000));
    }
}