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

module.exports = {
    name: 'unbaboon',
    description: 'Restore the roles of a user that were previously removed by the baboon command and remove the role with ID 1160622954082738347. If no cached roles are found, assign a default role.',
    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 are not alpha enough to unbaboon other users.');
        }

        try {
            // Identify the target user
            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('Please tag the baboon you wish to rewild.');
            }

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

            // Retrieve the bot's own member object
            const botMember = await message.guild.members.fetch(message.client.user.id);

            // Check if the bot has MANAGE_ROLES permission
            if (!botMember.permissions.has('MANAGE_ROLES')) {
                return message.reply('My kung fu is not strong enough.');
            }

            const roleID = '1160622954082738347';
            const defaultRoleID = '964354344948494416';
            const role = message.guild.roles.cache.get(roleID);
            const defaultRole = message.guild.roles.cache.get(defaultRoleID);

            if (!role) {
                return message.reply('Role not found.');
            }
            if (!defaultRole) {
                return message.reply('Default role not found.');
            }

            const filePath = path.join(__dirname, '../roles_backup.json');
            if (!fs.existsSync(filePath)) {
                return message.reply('No role backup file found.');
            }

            const rolesBackup = JSON.parse(fs.readFileSync(filePath, 'utf8'));
            const rolesArray = rolesBackup[target.id];

            await target.roles.remove(role);
            if (rolesArray && rolesArray.length > 0) {
                await target.roles.add(rolesArray);
                message.channel.send(`${target.displayName} has been rewilded.`);
            } else {
                await target.roles.add(defaultRole);
                message.channel.send(`${target.displayName} has returned to civilization.`);
            }

            delete rolesBackup[target.id];
            fs.writeFileSync(filePath, JSON.stringify(rolesBackup, null, 2), 'utf8');
        } catch (error) {
            console.error('An error occurred:', error);
            message.channel.send('There was an error trying to restore the roles.');
        }
    },
};
