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('warn')
        .setDescription('Avertir un membre.')
        .addUserOption(option =>
            option.setName('target')
                .setDescription('Le membre à avertir')
                .setRequired(true))
        .addStringOption(option =>
            option.setName('reason')
                .setDescription('Raison de l\'avertissement')
                .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.id === interaction.user.id) return interaction.editReply({ content: '❌ Tu ne peux pas t\'avertir toi-même.' });

        try {
            const [warnRows] = await db.query(
                'SELECT COUNT(*) as count FROM logs WHERE userId = ? AND guildId = ? AND action = ?',
                [target.id, interaction.guild.id, 'Avertissement']
            );
            const warnCount = warnRows[0].count + 1;

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

            const embed = new EmbedBuilder()
                .setAuthor({ name: target.displayName, iconURL: target.displayAvatarURL({ dynamic: true }) })
                .setTitle(`${emojis.warn} Utilisateur Averti`)
                .setColor(colors.warn)
                .setThumbnail(target.displayAvatarURL({ dynamic: true }))
                .setDescription(`${target.toString()} a reçu un avertissement.`)
                .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: '🔢 Nombre d\'avertissements', value: `\`${warnCount}\``, 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] });

            try {
                const dmEmbed = new EmbedBuilder()
                    .setTitle(`${emojis.warn} Tu as reçu un avertissement`)
                    .setColor(colors.warn)
                    .setDescription(`Tu as été averti sur **${interaction.guild.name}**`)
                    .addFields(
                        { name: '📝 Raison', value: reason, inline: false },
                        { name: '🔢 Nombre d\'avertissements', value: `${warnCount}`, inline: true }
                    )
                    .setFooter({ text: interaction.guild.name, iconURL: interaction.guild.iconURL({ dynamic: true }) })
                    .setTimestamp();
                await target.send({ embeds: [dmEmbed] });
            } catch { /* DMs fermés */ }

            const logEmbed = new EmbedBuilder()
                .setAuthor({ name: interaction.user.displayName, iconURL: interaction.user.displayAvatarURL({ dynamic: true }) })
                .setTitle(`${emojis.warn} Avertissement`)
                .setColor(colors.warn)
                .setThumbnail(target.displayAvatarURL({ dynamic: true }))
                .setDescription(`${target.toString()} a reçu un avertissement.`)
                .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: '🔢 Nombre d\'avertissements', value: `\`${warnCount}\``, 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 warn:', err);
            await interaction.editReply({ content: `❌ Erreur: ${err.message}` });
        }
    },
};