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 baboonRoleID = '1160622954082738347';
        const defaultRoleID = '964354344948494416';
        const rolesBackupPath = path.join(__dirname, '../roles_backup.json');

        if (!message.member.permissions.has('MANAGE_ROLES')) {
            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('Please mention a user or reply to their message to use this command.');
        }

        if (!message.guild.me.permissions.has('MANAGE_ROLES')) {
            return message.reply('I do not have permission to manage roles.');
        }

        const baboonRole = message.guild.roles.cache.get(baboonRoleID);
        const defaultRole = message.guild.roles.cache.get(defaultRoleID);
        if (!baboonRole) {
            return message.reply('Baboon role not found.');
        }
        if (!defaultRole) {
            return message.reply('Default role not found.');
        }

        let rolesBackup = {};
        if (fs.existsSync(rolesBackupPath)) {
            rolesBackup = JSON.parse(fs.readFileSync(rolesBackupPath, 'utf8'));
        } else {
            return message.reply('No role backup file found.');
        }

        const rolesArray = rolesBackup[target.id];

        try {
            await target.roles.remove(baboonRole);
            if (rolesArray && rolesArray.length > 0) {
                await target.roles.add(rolesArray);
                message.channel.send(`Roles restored to ${target.displayName}.`);
            } else {
                await target.roles.add(defaultRole);
                message.channel.send(`${target.displayName} is now assigned the default role.`);
            }

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