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('purge')
        .setDescription('Supprimer les messages d\'un utilisateur dans un canal.')
        .addUserOption(option =>
            option.setName('target')
                .setDescription('L\'utilisateur dont supprimer les messages')
                .setRequired(true))
        .addIntegerOption(option =>
            option.setName('amount')
                .setDescription('Nombre de messages à vérifier (1-100)')
                .setRequired(true)
                .setMinValue(1)
                .setMaxValue(100))
        .addStringOption(option =>
            option.setName('reason')
                .setDescription('Raison de la purge')
                .setRequired(false))
        .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages),

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

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

        if (!interaction.channel.isTextBased()) {
            return interaction.editReply({ content: '❌ Cette commande ne peut être utilisée que dans un canal texte.' });
        }

        try {
            const messages = await interaction.channel.messages.fetch({ limit: amount });
            const messagesToDelete = messages.filter(msg => msg.author.id === target.id);

            const filteredMessages = messagesToDelete.filter(msg => {
                const msgAge = Date.now() - msg.createdTimestamp;
                return msgAge < 14 * 24 * 60 * 60 * 1000;
            });

            if (filteredMessages.size === 0) {
                return interaction.editReply({ content: `❌ Aucun message à supprimer de ${target.tag} (les messages de plus de 14 jours ne peuvent pas être supprimés).` });
            }

            await interaction.channel.bulkDelete(filteredMessages, true);

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

            const embed = new EmbedBuilder()
                .setAuthor({ name: target.displayName, iconURL: target.displayAvatarURL({ dynamic: true }) })
                .setTitle(`${emojis.success} Messages Supprimés`)
                .setColor(colors.success)
                .setDescription(`**${filteredMessages.size}** message(s) de ${target.toString()} supprimé(s).`)
                .setThumbnail(target.displayAvatarURL({ dynamic: true }))
                .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: '📊 Messages supprimés', value: `\`${filteredMessages.size}\``, 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.success} Purge`)
                .setColor(colors.success)
                .setThumbnail(target.displayAvatarURL({ dynamic: true }))
                .setDescription(`**${filteredMessages.size}** message(s) de ${target.toString()} supprimé(s).`)
                .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: '📊 Messages supprimés', value: `\`${filteredMessages.size}\``, 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 purge:', err);
            if (err.code === 50034) {
                await interaction.editReply({ content: '❌ Les messages de plus de 14 jours ne peuvent pas être supprimés.' });
            } else {
                await interaction.editReply({ content: `❌ Échec de la purge: ${err.message}` });
            }
        }
    },
};