const { SlashCommandBuilder, MessageFlags } = require('discord.js'); // Import MessageFlags
const logger = require('../utils/logger');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('leave')
        .setDescription('Leaves the current voice channel'),
    async execute(interaction, client) { // Added client parameter
        // Use flags for ephemeral deferral
        await interaction.deferReply({ flags: MessageFlags.Ephemeral }); 

        // Get the Shoukaku player manager
        const musicPlayer = interaction.client.player;
        if (!musicPlayer) {
            logger.error('Music player not initialized on client object!');
            return interaction.editReply('The music player is not ready yet.');
        }

        // Get the player for this guild using Shoukaku manager
        const player = musicPlayer.getPlayer(interaction.guildId);

        // Check if the player exists (Shoukaku player object has voiceChannel property)
        if (!player || !player.voiceChannel) {
            return interaction.editReply('I am not currently in a voice channel!');
        }

        // Optional: Check if the user is in the same channel as the bot
        // const memberVoiceChannel = interaction.member?.voice?.channelId;
        // if (memberVoiceChannel !== player.voiceChannel) {
        //     return interaction.editReply('You need to be in the same voice channel as me to make me leave!');
        // }

        try {
            const channelId = player.voiceChannel; // Get channel ID from Shoukaku player
            const channel = client.channels.cache.get(channelId);
            const channelName = channel ? channel.name : `ID: ${channelId}`; // Get channel name if possible

            player.destroy(); // Use Shoukaku player's destroy method
            logger.info(`Player destroyed and left voice channel ${channelName} in guild ${interaction.guild.name} (${interaction.guildId}) by user ${interaction.user.tag}`);
            await interaction.editReply(`Left ${channelName}.`);

        } catch (error) {
            logger.error(`Error destroying player for guild ${interaction.guildId}: ${error.message}`, error);
            // Attempt to reply even if destroy failed partially
            await interaction.editReply('An error occurred while trying to leave the voice channel.').catch(e => logger.error(`Failed to send error reply for leave command: ${e.message}`));
        }
    },
};
