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('untimeout')
        .setDescription('Retirer le timeout d\'un membre.')
        .addUserOption(option =>
            option.setName('target')
                .setDescription('Le membre à dé-timeout')
                .setRequired(true))
        .addStringOption(option =>
            option.setName('reason')
                .setDescription('Raison de la levée du timeout')
                .setRequired(false))
        .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers),

    async execute(interaction) {
        const target = interaction.options.getUser('target');
        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 en timeout.' });
        }

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

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

            const embed = new EmbedBuilder()
                .setTitle(`${emojis.success} Timeout Retiré`)
                .setColor(colors.success)
                .setThumbnail(target.displayAvatarURL({ dynamic: true }))
                .addFields(
                    { name: '👤 Utilisateur', value: `<@${target.id}> (${target.tag})`, inline: true },
                    { name: '✅ Modérateur', value: `<@${interaction.user.id}> (${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}` })
                .setTimestamp();

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

            const logEmbed = new EmbedBuilder()
                .setTitle(`${emojis.success} Timeout Retiré`)
                .setColor(colors.success)
                .addFields(
                    { name: '👤 Utilisateur', value: `<@${target.id}> (${target.tag})`, inline: true },
                    { name: '✅ Modérateur', value: `<@${interaction.user.id}> (${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} | Serveur: ${interaction.guild.name}` })
                .setTimestamp();
            await sendLog(interaction.guild, { embeds: [logEmbed] });

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