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('changesanction')
        .setDescription('Changer la raison d\'une sanction.')
        .addUserOption(option =>
            option.setName('user')
                .setDescription('L\'utilisateur concerné')
                .setRequired(true))
        .addIntegerOption(option =>
            option.setName('sanction_id')
                .setDescription('L\'ID DB de la sanction (visible dans /casier, ex: ID: 123)')
                .setRequired(true))
        .addStringOption(option =>
            option.setName('new_reason')
                .setDescription('La nouvelle raison')
                .setRequired(true))
        .setDefaultMemberPermissions(PermissionFlagsBits.ModerateMembers),

    async execute(interaction) {
        const target = interaction.options.getUser('user');
        const sanctionId = interaction.options.getInteger('sanction_id');
        const newReason = interaction.options.getString('new_reason');

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

        try {
            const [sanctionRows] = await db.query(
                'SELECT * FROM logs WHERE id = ? AND userId = ? AND guildId = ?',
                [sanctionId, target.id, interaction.guild.id]
            );

            if (!sanctionRows.length) {
                const [allUserLogs] = await db.query(
                    'SELECT id, action, guildId FROM logs WHERE id = ? AND userId = ?',
                    [sanctionId, target.id]
                );
                
                if (allUserLogs.length > 0) {
                    const log = allUserLogs[0];
                    const guildName = interaction.client.guilds.cache.get(log.guildId)?.name || 'Serveur inconnu';
                    return interaction.editReply({ 
                        content: `❌ La sanction avec l'ID ${sanctionId} existe, mais elle appartient au serveur "${guildName}" (guildId: ${log.guildId}), pas à "${interaction.guild.name}" (guildId: ${interaction.guild.id}).` 
                    });
                }
                
                return interaction.editReply({ 
                    content: `❌ Aucune sanction trouvée avec l'ID ${sanctionId} pour ${target.tag}.\n\n💡 **Astuce:** Utilise l'ID DB visible dans \`/casier\` (ex: \`#1 (ID: 123)\` → utilise \`123\`).` 
                });
            }

            const sanction = sanctionRows[0];

            if (sanction.action === 'Modification de sanction' || 
                sanction.action === 'Révocation de sanction' || 
                sanction.action === 'Modification de mute') {
                return interaction.editReply({ content: `❌ Cette entrée est une modification, pas une sanction. Utilise l'ID d'une vraie sanction.` });
            }
            const oldReason = sanction.reason;

            await db.query(
                'UPDATE logs SET reason = ?, modId = ?, modTag = ? WHERE id = ?',
                [newReason, interaction.user.id, interaction.user.tag, sanction.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, 'Modification de sanction', `Ancienne raison: ${oldReason} → Nouvelle raison: ${newReason}`, null, interaction.guild.id, Date.now()]
            );

            const embed = new EmbedBuilder()
                .setTitle(`${emojis.success} Sanction Modifiée`)
                .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: '📝 Ancienne raison', value: oldReason || 'N/A', inline: false },
                    { name: '📝 Nouvelle raison', value: newReason, inline: false },
                    { name: '🆔 ID Sanction', value: `${sanction.id}`, inline: true },
                    { 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} Modification de Sanction`)
                .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: '📝 Ancienne raison', value: oldReason || 'N/A', inline: false },
                    { name: '📝 Nouvelle raison', value: newReason, inline: false },
                    { name: '🆔 ID Sanction', value: `${sanction.id}`, inline: true },
                    { 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 changesanction:', err);
            await interaction.editReply({ content: `❌ Échec de la modification de la sanction: ${err.message}` });
        }
    },
};