const { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder, 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('unmute')
        .setDescription('Démuter un membre du serveur.')
        .addUserOption(option =>
            option.setName('user')
                .setDescription('Le membre à démuter')
                .setRequired(true))
        .addStringOption(option =>
            option.setName('reason')
                .setDescription('Raison du démute')
                .setRequired(false))
        .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers),

    async execute(interaction) {
        const target = interaction.options.getUser('user');
        const reason = interaction.options.getString('reason') || 'Aucune raison fournie';

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

        if (!target) return interaction.editReply({ content: '❌ Aucun utilisateur spécifié !' });

        const member = await interaction.guild.members.fetch(target.id).catch(() => null);
        if (!member) return interaction.editReply({ content: '❌ Cet utilisateur n\'est pas sur le serveur.' });

        if (!member.communicationDisabledUntilTimestamp || member.communicationDisabledUntilTimestamp < Date.now()) {
            return interaction.editReply({ content: '❌ Cet utilisateur n\'est pas muté.' });
        }

        try {
            await member.timeout(null, `Démuté par ${interaction.user.tag}: ${reason}`);

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

            await db.query(
                `INSERT INTO logs (userId, userTag, modId, modTag, action, reason, type, guildId, timestamp)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                [target.id, target.tag, interaction.user.id, interaction.user.tag, 'Unmute', reason, null, interaction.guild.id, Date.now()]
            );

            const embed = new EmbedBuilder()
                .setAuthor({ name: target.displayName, iconURL: target.displayAvatarURL({ dynamic: true }) })
                .setTitle(`${emojis.unmute} Utilisateur Démuté`)
                .setColor(colors.unmute)
                .setThumbnail(target.displayAvatarURL({ dynamic: true }))
                .setDescription(`${target.toString()} a été démuté.`)
                .addFields(
                    { name: '👤 Utilisateur', value: `${target.toString()}\n\`${target.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: ${target.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.unmute} Unmute`)
                .setColor(colors.unmute)
                .setThumbnail(target.displayAvatarURL({ dynamic: true }))
                .setDescription(`${target.toString()} a été démuté.`)
                .addFields(
                    { name: '👤 Utilisateur', value: `${target.toString()}\n\`${target.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: ${target.id} • ${interaction.guild.name}` })
                .setTimestamp();
            
            await sendLog(interaction.guild, { embeds: [logEmbed] });

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