const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits, MessageFlags } = require('discord.js');
const db = require('../../functions/database/db.js');
const { sendLog } = require('../../utils/helpers');
const { colors, emojis } = require('../../utils/constants');

module.exports = {
    category: 'moderation',
    data: new SlashCommandBuilder()
        .setName('unban')
        .setDescription('Débannir un utilisateur par son ID ou son tag.')
        .addStringOption(option =>
            option.setName('user')
                .setDescription('L\'ID ou le tag (Username#1234) de l\'utilisateur à débannir')
                .setRequired(true))
        .setDefaultMemberPermissions(PermissionFlagsBits.BanMembers),

    async execute(interaction) {
        await interaction.deferReply({ flags: MessageFlags.Ephemeral });

        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({ content: '❌ Cet utilisateur n\'est pas banni.' });

            const reason = `Débanni par ${interaction.user.tag}`;
            await interaction.guild.members.unban(bannedUser.user.id, reason);

            await db.query('DELETE FROM bans WHERE userId = ? AND guildId = ?', [bannedUser.user.id, interaction.guild.id]);

            const embed = new EmbedBuilder()
                .setAuthor({ name: bannedUser.user.displayName, iconURL: bannedUser.user.displayAvatarURL({ dynamic: true }) })
                .setTitle(`${emojis.unban} Utilisateur Débanni`)
                .setColor(colors.unban)
                .setThumbnail(bannedUser.user.displayAvatarURL({ dynamic: true }))
                .setDescription(`${bannedUser.user.toString()} a été débanni du serveur.`)
                .addFields(
                    { name: '👤 Utilisateur', value: `${bannedUser.user.toString()}\n\`${bannedUser.user.tag}\``, inline: true },
                    { name: '👮 Modérateur', value: `${interaction.user.toString()}\n\`${interaction.user.tag}\``, inline: true },
                    { name: '📝 Raison', value: reason, inline: false },
                    { name: '📅 Date', value: `<t:${Math.floor(Date.now() / 1000)}:F>`, inline: true }
                )
                .setFooter({ text: `ID: ${bannedUser.user.id} • ${interaction.guild.name}` })
                .setTimestamp();

            await interaction.editReply({ embeds: [embed] });

            const logEmbed = new EmbedBuilder()
                .setAuthor({ name: interaction.user.displayName, iconURL: interaction.user.displayAvatarURL({ dynamic: true }) })
                .setTitle(`${emojis.unban} Débannissement`)
                .setColor(colors.unban)
                .setThumbnail(bannedUser.user.displayAvatarURL({ dynamic: true }))
                .setDescription(`${bannedUser.user.toString()} a été débanni du serveur.`)
                .addFields(
                    { name: '👤 Utilisateur', value: `${bannedUser.user.toString()}\n\`${bannedUser.user.tag}\``, inline: true },
                    { name: '👮 Modérateur', value: `${interaction.user.toString()}\n\`${interaction.user.tag}\``, inline: true },
                    { name: '📝 Raison', value: reason, inline: false },
                    { name: '📅 Date', value: `<t:${Math.floor(Date.now() / 1000)}:F>`, inline: true }
                )
                .setFooter({ text: `ID: ${bannedUser.user.id} • ${interaction.guild.name}` })
                .setTimestamp();
            
            await sendLog(interaction.guild, { embeds: [logEmbed] });

            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, 'Débannissement', reason, null, interaction.guild.id, Date.now()]
            );

        } catch (err) {
            console.error('Erreur unban:', err);
            await interaction.editReply({ content: `❌ Erreur: ${err.message}` });
        }
    },
};