const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits } = require('discord.js');
const db = require('../../functions/database/db.js');

module.exports = {
    category: 'moderation',
    data: new SlashCommandBuilder()
        .setName('unban')
        .setDescription('Unban a user by their ID or tag.')
        .addStringOption(option =>
            option.setName('user')
                .setDescription('The ID or tag (Username#1234) of the user to unban')
                .setRequired(true))
        .setDefaultMemberPermissions(PermissionFlagsBits.BanMembers),

    async execute(interaction) {
        await interaction.deferReply();

        const input = interaction.options.getString('user').trim();

        try {
            const bannedUsers = await interaction.guild.bans.fetch();
            const bannedUser = bannedUsers.find(b =>
                b.user.id === input || b.user.tag.toLowerCase() === input.toLowerCase()
            );
            if (!bannedUser) return interaction.editReply('❌ This user is not banned.');

            // Récupération depuis MySQL
            const [rows] = await db.query('SELECT * FROM bans WHERE userId = ?', [bannedUser.user.id]);
            const banRecord = rows[0];

            const reason = `Unbanned by ${interaction.user.tag}`;
            await interaction.guild.members.unban(bannedUser.user.id, reason);

            if (banRecord) await db.query('DELETE FROM bans WHERE userId = ?', [bannedUser.user.id]);

            await interaction.editReply(`✅ Successfully unbanned ${bannedUser.user.tag}`);

            const logChannel = interaction.guild.channels.cache.find(ch => ch.name === 'logs');
            if (logChannel) {
                const embed = new EmbedBuilder()
                    .setTitle('User Unbanned')
                    .setColor('Green')
                    .addFields(
                        { name: 'Membre Banni', value: `<@${bannedUser.user.id}> (${bannedUser.user.tag})`, inline: true },
                        { name: 'Modérateur', value: `<@${interaction.user.id}> (${interaction.user.tag})`, inline: true },
                        { name: 'Date', value: new Date().toLocaleString(), inline: true },
                        { name: 'Guild', value: interaction.guild.name, inline: true }
                    )
                    .setTimestamp();
                logChannel.send({ embeds: [embed] });
            }

            // Log dans la DB avec guildId
            await db.query(
                `INSERT INTO logs (userId, userTag, modId, modTag, action, reason, type, guildId, timestamp)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                [bannedUser.user.id, bannedUser.user.tag, interaction.user.id, interaction.user.tag, 'unban', reason, null, interaction.guild.id, Date.now()]
            );

        } catch (err) {
            console.error(err);
            await interaction.editReply('❌ Failed to unban the user.');
        }
    }
};
