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

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

        const member = interaction.member;
        const voiceChannel = member?.voice?.channel;

        // 1. Check if user is in a voice channel
        if (!voiceChannel) {
            return interaction.editReply('You need to be in a voice channel to use this command!');
        }

        // 2. Check bot permissions
        const permissions = voiceChannel.permissionsFor(client.user);
        if (!permissions.has(PermissionFlagsBits.Connect)) {
            return interaction.editReply('I need permission to **connect** to your voice channel!');
        }
        if (!permissions.has(PermissionFlagsBits.Speak)) {
            return interaction.editReply('I need permission to **speak** in your voice channel!');
        }
        // Ensure it's a voice channel (not stage, etc.) although erela might handle this
        if (voiceChannel.type !== ChannelType.GuildVoice) {
             return interaction.editReply('I can only join standard voice channels.');
        }

        // Get the initialized Shoukaku player manager from the client object
        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. Please try again shortly.');
        }

        // 3. Get or create the player and connect using Shoukaku
        let player = musicPlayer.getPlayer(interaction.guildId);

        if (!player) {
            try {
                // Create player using the Shoukaku manager
                player = await musicPlayer.createPlayer({
                    guildId: interaction.guildId,
                    textChannel: interaction.channelId,
                    voiceChannel: voiceChannel.id
                });
                // Connection is handled within createPlayer
                logger.info(`Created player and connected to voice channel ${voiceChannel.name} (${voiceChannel.id}) in guild ${interaction.guild.name} (${interaction.guildId})`);
                await interaction.editReply(`Joined ${voiceChannel.name}! Ready to play music.`);

            } catch (error) {
                logger.error(`Failed to create/connect player for guild ${interaction.guildId}: ${error.message}`, error);
                // Player destruction is handled internally if creation fails or via destroy method
                return interaction.editReply('An error occurred while trying to join the voice channel.');
            }
        } else {
            // If player exists but is in a different channel
            if (player.voiceChannel !== voiceChannel.id) {
                // Destroy the old player and create a new one in the correct channel
                player.destroy();
                try {
                    player = await musicPlayer.createPlayer({
                        guildId: interaction.guildId,
                        textChannel: interaction.channelId,
                        voiceChannel: voiceChannel.id
                    });
                    logger.info(`Moved player to voice channel ${voiceChannel.name} (${voiceChannel.id}) in guild ${interaction.guildId}`);
                    await interaction.editReply(`Moved to ${voiceChannel.name}!`);
                } catch (error) {
                     logger.error(`Failed to move player for guild ${interaction.guildId}: ${error.message}`, error);
                     return interaction.editReply('An error occurred while trying to move to the voice channel.');
                }
            } else {
                 // Already in the correct channel
                 await interaction.editReply(`I'm already in ${voiceChannel.name}!`);
            }
             // Update text channel if needed (Shoukaku player object stores textChannel)
             if (player.textChannel !== interaction.channelId) {
                player.textChannel = interaction.channelId; // Directly update the property
                logger.debug(`Updated player text channel to ${interaction.channel.name} (${interaction.channelId}) in guild ${interaction.guildId}`);
             }
        }
    },
};
