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

module.exports = {
    category: 'moderation',
    data: new SlashCommandBuilder()
        .setName('mute')
        .setDescription('Muter un membre du serveur.')
        .addUserOption(option =>
            option.setName('user')
                .setDescription('Le membre à muter')
                .setRequired(true))
        .addStringOption(option =>
            option.setName('duration')
                .setDescription('Durée du mute (ex: 5m, 1h, 1d, max 28j)')
                .setRequired(true))
        .addStringOption(option =>
            option.setName('reason')
                .setDescription('Raison du mute')
                .setRequired(false))
        .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers),

    async execute(interaction) {
        const target = interaction.options.getUser('user');
        const durationInput = interaction.options.getString('duration');
        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.guild.ownerId) return interaction.editReply({ content: '❌ Tu ne peux pas muter le propriétaire du serveur.' });
        if (member.id === interaction.user.id) return interaction.editReply({ content: '❌ Tu ne peux pas te muter toi-même.' });
        
        if (member.roles.highest.position >= interaction.member.roles.highest.position && interaction.guild.ownerId !== interaction.user.id) {
            return interaction.editReply({ content: '❌ Tu ne peux pas muter cet utilisateur car il a un rôle supérieur ou égal au tien.' });
        }
        if (!member.moderatable) {
            return interaction.editReply({ content: '❌ Je n\'ai pas les permissions nécessaires pour muter cet utilisateur.' });
        }

        const durationMs = parseDuration(durationInput);
        if (!durationMs) return interaction.editReply({ content: '❌ Durée invalide. Utilise un format comme: 5m, 1h, 2d (max 28 jours).' });

        const maxDuration = 28 * 24 * 60 * 60 * 1000;
        if (durationMs > maxDuration) return interaction.editReply({ content: '❌ La durée maximum est de 28 jours.' });

        const unmuteDate = Date.now() + durationMs;
        const type = 'Temporary'; // Timeout est toujours temporaire

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

            await db.query(
                `INSERT INTO mutes (userId, guildId, reason, modId, modTag, timestamp, unmuteDate, type)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                 ON DUPLICATE KEY UPDATE reason=VALUES(reason), modId=VALUES(modId), modTag=VALUES(modTag), timestamp=VALUES(timestamp), unmuteDate=VALUES(unmuteDate), type=VALUES(type)`,
                [target.id, interaction.guild.id, reason, interaction.user.id, interaction.user.tag, Date.now(), unmuteDate, type]
            );

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

            const embed = new EmbedBuilder()
                .setAuthor({ name: target.displayName, iconURL: target.displayAvatarURL({ dynamic: true }) })
                .setTitle(`${emojis.mute} Utilisateur Muté`)
                .setColor(colors.mute)
                .setThumbnail(target.displayAvatarURL({ dynamic: true }))
                .setDescription(`${target.toString()} a été 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: '⏰ Durée', value: `\`${formatDuration(durationMs)}\``, inline: true },
                    { name: '📝 Raison', value: reason, inline: false },
                    { name: '📅 Jusqu\'à', value: `<t:${Math.floor(unmuteDate / 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.mute} Mute`)
                .setColor(colors.mute)
                .setThumbnail(target.displayAvatarURL({ dynamic: true }))
                .setDescription(`${target.toString()} a été 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: '⏰ Durée', value: `\`${formatDuration(durationMs)}\``, inline: true },
                    { name: '📝 Raison', value: reason, inline: false },
                    { name: '📅 Jusqu\'à', value: `<t:${Math.floor(unmuteDate / 1000)}:F>`, inline: true }
                )
                .setFooter({ text: `ID: ${target.id} • ${interaction.guild.name}` })
                .setTimestamp();
            
            await sendLog(interaction.guild, { embeds: [logEmbed] });

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