package party.cybsec.griefdetect.commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import party.cybsec.griefdetect.GriefDetectPlugin;
import party.cybsec.griefdetect.config.PluginConfig;
import party.cybsec.griefdetect.core.ModuleManager;
import party.cybsec.griefdetect.core.PermissionManager;
import party.cybsec.griefdetect.core.WebhookManager;
import party.cybsec.griefdetect.core.ChatAlertManager;

/**
 * Reload command for GriefDetect plugin.
 * Permission-protected, reloads config and restarts modules safely.
 */
public class ReloadCommand implements CommandExecutor {
    
    private final GriefDetectPlugin plugin;
    private final PermissionManager permissionManager;
    private final PluginConfig config;
    private final ModuleManager moduleManager;
    private final WebhookManager webhookManager;
    private final ChatAlertManager chatAlertManager;
    
    public ReloadCommand(GriefDetectPlugin plugin) {
        this.plugin = plugin;
        this.permissionManager = plugin.getPermissionManager();
        this.config = plugin.getPluginConfig();
        this.moduleManager = plugin.getModuleManager();
        this.webhookManager = plugin.getWebhookManager();
        this.chatAlertManager = plugin.getChatAlertManager();
    }
    
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        // Check permissions
        if (sender instanceof Player) {
            Player player = (Player) sender;
            if (!permissionManager.canReload(player)) {
                sender.sendMessage("§cYou don't have permission to use this command.");
                return true;
            }
        }
        
        // Perform reload
        reloadPlugin(sender);
        return true;
    }
    
    /**
     * Reload the plugin configuration and modules.
     */
    private void reloadPlugin(CommandSender sender) {
        try {
            // Reload configuration
            config.reload();
            
            // Reload modules
            moduleManager.reloadModules();
            
            // Reload webhook manager
            webhookManager.reload();
            
            // Reload chat alert manager
            chatAlertManager.reload();
            
            // Clear permission cache
            permissionManager.clearAllCache();
            
            // Send success message
            sender.sendMessage("§aGriefDetect configuration reloaded successfully!");
            plugin.getLogger().info("Plugin reloaded by " + sender.getName());
            
        } catch (Exception e) {
            sender.sendMessage("§cError reloading plugin: " + e.getMessage());
            plugin.getLogger().severe("Error reloading plugin: " + e.getMessage());
            e.printStackTrace();
        }
    }
}