const fs = require('fs');
const path = require('path');

module.exports = {
    name: 'baboon',
    description: 'Strip all roles from a user and assign the role with ID 1160622954082738347.',
    async execute(message) {
        const authorizedRoles = ['827303828884946944', '827332588803850270'];
        const userRoles = message.member.roles.cache.map(role => role.id);

        console.log('User roles:', userRoles); // Debugging line
        console.log('Authorized roles:', authorizedRoles); // Debugging line

        if (!userRoles.some(role => authorizedRoles.includes(role))) {
            return message.reply('You do not have permission to use this command.');
        }

        let target;
        if (message.mentions.members.first()) {
            target = message.mentions.members.first();
        } else if (message.reference) {
            target = await message.channel.messages.fetch(message.reference.messageId).then(msg => msg.member);
        } else {
            return message.reply('You have not targeted a user to baboon.');
        }

        console.log('Target user identified:', target.user.tag); // Debugging line

        const roleID = '1160622954082738347';
        const role = message.guild.roles.cache.get(roleID);
        if (!role) {
            return message.reply('Role not found.');
        }

        const previousRoles = target.roles.cache.filter(r => r.name !== '@everyone');
        const rolesArray = previousRoles.map(role => role.id);

        const filePath = path.join(__dirname, '../roles_backup.json');
        let rolesBackup = {};

        if (fs.existsSync(filePath)) {
            rolesBackup = JSON.parse(fs.readFileSync(filePath, 'utf8'));
        }

        rolesBackup[target.id] = rolesArray;
        fs.writeFileSync(filePath, JSON.stringify(rolesBackup, null, 2), 'utf8');

        try {
            await target.roles.remove(rolesArray);
            await target.roles.add(role);
            
            const logChannelID = '1028786996505759794'; // Replace with your actual channel ID
            const logChannel = message.guild.channels.cache.get(logChannelID);
            
            if (logChannel) {
                message.channel.send(`${target.displayName} has become a ${role.name}! Check them out in ${logChannel.toString()}`);
            } else {
                console.error('Log channel not found');
            }
        } catch (error) {
            console.error(error);
            message.channel.send('Sorry, I am having trouble with my baboon gun.');
        }
    },
};
