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

module.exports = {
    category: 'xp',
    data: new SlashCommandBuilder()
        .setName('xpexclude')
        .setDescription('Gérer les salons exclus de l\'XP (Admin uniquement)')
        .addSubcommand(subcommand =>
            subcommand
                .setName('add')
                .setDescription('Exclure un salon de l\'XP')
                .addChannelOption(option =>
                    option.setName('channel')
                        .setDescription('Le salon à exclure')
                        .setRequired(true))
                .addStringOption(option =>
                    option.setName('reason')
                        .setDescription('Raison de l\'exclusion')
                        .setRequired(false)))
        .addSubcommand(subcommand =>
            subcommand
                .setName('remove')
                .setDescription('Retirer un salon de l\'exclusion')
                .addChannelOption(option =>
                    option.setName('channel')
                        .setDescription('Le salon à retirer')
                        .setRequired(true)))
        .addSubcommand(subcommand =>
            subcommand
                .setName('list')
                .setDescription('Liste des salons exclus')),
    async execute(interaction) {
        await interaction.deferReply({ flags: MessageFlags.Ephemeral });
        
        if (!interaction.member.permissions.has(PermissionFlagsBits.Administrator)) {
            return interaction.editReply({
                content: '❌ Tu n\'as pas la permission d\'utiliser cette commande. (Administrateur requis)'
            });
        }
        
        const subcommand = interaction.options.getSubcommand();
        
        try {
            if (subcommand === 'add') {
                const channel = interaction.options.getChannel('channel');
                const reason = interaction.options.getString('reason') || 'Aucune raison fournie';
                
                if (!channel.isTextBased()) {
                    return interaction.editReply({
                        content: '❌ Le salon doit être un canal texte.'
                    });
                }
                
                const excluded = await isChannelExcluded(channel.id, interaction.guild.id);
                if (excluded) {
                    return interaction.editReply({
                        content: `❌ Le salon ${channel.toString()} est déjà exclu de l'XP.`
                    });
                }
                
                await db.query(
                    'INSERT INTO xp_excluded_channels (channelId, guildId, reason, addedBy, addedAt) VALUES (?, ?, ?, ?, ?)',
                    [channel.id, interaction.guild.id, reason, interaction.user.id, Date.now()]
                );
                
                const embed = new EmbedBuilder()
                    .setTitle(`${emojis.success} Salon Exclu`)
                    .setColor(colors.success)
                    .setDescription(`Le salon ${channel.toString()} a été exclu de l'XP.`)
                    .addFields(
                        { name: '📝 Raison', value: reason, inline: false }
                    )
                    .setFooter({ text: `${interaction.guild.name} • Système XP` })
                    .setTimestamp();
                
                await interaction.editReply({ embeds: [embed] });
                
            } else if (subcommand === 'remove') {
                const channel = interaction.options.getChannel('channel');
                
                const excluded = await isChannelExcluded(channel.id, interaction.guild.id);
                if (!excluded) {
                    return interaction.editReply({
                        content: `❌ Le salon ${channel.toString()} n'est pas exclu de l'XP.`
                    });
                }
                
                await db.query(
                    'DELETE FROM xp_excluded_channels WHERE channelId = ? AND guildId = ?',
                    [channel.id, interaction.guild.id]
                );
                
                const embed = new EmbedBuilder()
                    .setTitle(`${emojis.success} Exclusion Retirée`)
                    .setColor(colors.success)
                    .setDescription(`Le salon ${channel.toString()} n'est plus exclu de l'XP.`)
                    .setFooter({ text: `${interaction.guild.name} • Système XP` })
                    .setTimestamp();
                
                await interaction.editReply({ embeds: [embed] });
                
            } else if (subcommand === 'list') {
                const [excludedChannels] = await db.query(
                    'SELECT * FROM xp_excluded_channels WHERE guildId = ?',
                    [interaction.guild.id]
                );
                
                if (excludedChannels.length === 0) {
                    return interaction.editReply({
                        content: '✅ Aucun salon n\'est exclu de l\'XP.'
                    });
                }
                
                const description = excludedChannels.map(ch => {
                    const channel = interaction.guild.channels.cache.get(ch.channelId);
                    return `• ${channel ? channel.toString() : `ID: ${ch.channelId}`} - ${ch.reason || 'Aucune raison'}`;
                }).join('\n');
                
                const embed = new EmbedBuilder()
                    .setAuthor({ 
                        name: interaction.guild.name, 
                        iconURL: interaction.guild.iconURL({ dynamic: true }) || undefined 
                    })
                    .setTitle('📋 Salons Exclus de l\'XP')
                    .setColor(colors.xp)
                    .setDescription(description || 'Aucun salon exclu')
                    .setFooter({ text: `${excludedChannels.length} salon(s) exclu(s)` })
                    .setTimestamp();
                
                await interaction.editReply({ embeds: [embed] });
            }
        } catch (err) {
            console.error('Erreur xpexclude:', err);
            await interaction.editReply({ content: `❌ Erreur: ${err.message}` });
        }
    },
};