const { Events } = require('discord.js');
const logger = require('../utils/logger');

module.exports = {
    name: Events.VoiceStateUpdate,
    execute(oldState, newState, client) { // Added client parameter
        // Shoukaku handles voice state updates internally via its connector.
        // We don't need to manually pass the update like with Erela.js.
        // The warning about Erela.js manager not being initialized can be ignored/removed.

        // Custom logic for player cleanup based on voice state changes.
        const musicPlayer = client.player;
        if (!musicPlayer) {
            // Player manager might not be ready yet, especially during startup.
            // logger.debug('Voice state update received, but Shoukaku player manager is not ready yet.');
            return;
        }

        const player = musicPlayer.getPlayer(newState.guild.id);
        if (!player) return; // No active player for this guild

        // Check if the bot was disconnected (newState has no channelId for the bot)
        if (newState.id === client.user.id && !newState.channelId && oldState.channelId === player.voiceChannel) {
            logger.info(`Bot was disconnected from voice channel ${oldState.channel?.name || oldState.channelId} in guild ${newState.guild.id}. Destroying player.`);
            player.destroy(); // Use Shoukaku player's destroy method
            return; // Exit early as the player is destroyed
        }

        // Check if the bot's channel is now empty (excluding the bot itself)
        const channel = client.channels.cache.get(player.voiceChannel);
        // Ensure the channel exists and the update is relevant to the bot's channel
        if (channel && (newState.channelId === player.voiceChannel || oldState.channelId === player.voiceChannel)) {
             // Fetch members again to ensure freshness after the update
            const members = channel.members;
            if (members.size === 1 && members.has(client.user.id)) {
                logger.info(`Voice channel ${channel.name} (${player.voiceChannel}) in guild ${newState.guild.id} is now empty (only bot left). Destroying player.`);
                // Optional: Add a timeout before destroying
                // setTimeout(() => {
                //     const currentChannel = client.channels.cache.get(player.voiceChannel);
                //     const currentMembers = currentChannel?.members;
                //     if (currentMembers && currentMembers.size === 1 && currentMembers.has(client.user.id)) {
                //         logger.info(`Timeout finished: Destroying player in empty channel ${channel.name}.`);
                //         player.destroy();
                //     } else {
                //          logger.info(`Timeout finished: Channel ${channel.name} is no longer empty. Player not destroyed.`);
                //     }
                // }, 60000); // e.g., 1 minute timeout
                player.destroy(); // Destroy immediately for now
            }
        }
    },
};
