package com.firefrostgaming.rules;

import net.neoforged.bus.api.IEventBus;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.config.ModConfig;
import net.neoforged.fml.event.config.ModConfigEvent;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Mod("firefrostrules")
public class ServerRules {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServerRules.class);

    public ServerRules(IEventBus modEventBus, ModContainer modContainer) {
        modContainer.registerConfig(ModConfig.Type.COMMON, ServerRulesConfig.SPEC);
        modEventBus.addListener(this::onConfigLoaded);
        modEventBus.addListener(this::onConfigReload);
        NeoForge.EVENT_BUS.register(this);
        LOGGER.info("Firefrost Rules Mod Initialized.");
    }

    @SubscribeEvent
    public void onRegisterCommands(RegisterCommandsEvent event) {
        RulesCommand.register(event.getDispatcher());
        LOGGER.info("Registered /rules command.");
    }

    @SubscribeEvent
    public void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event) {
        CooldownManager.removePlayer(event.getEntity().getUUID());
    }

    private void onConfigLoaded(ModConfigEvent.Loading event) {
        if (event.getConfig().getSpec() == ServerRulesConfig.SPEC) {
            String token = ServerRulesConfig.BOT_TOKEN.get();
            if (token.equals("YOUR_TOKEN_HERE")) {
                LOGGER.warn("Rules mod is using default config values! Edit config/firefrostrules-common.toml");
            } else {
                LOGGER.info("Rules mod config loaded successfully. Channel: {}", ServerRulesConfig.CHANNEL_ID.get());
            }
        }
    }

    private void onConfigReload(ModConfigEvent.Reloading event) {
        LOGGER.info("Rules configuration reloaded! Invalidating cache.");
        RulesCache.invalidate();
    }
}
