const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits, ChannelType } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('config')
        .setDescription('Configure le bot (Admin uniquement)')
        .addSubcommand(subcommand =>
            subcommand
                .setName('suggestion')
                .setDescription('Configure le salon des suggestions')
                .addChannelOption(option =>
                    option.setName('salon')
                        .setDescription('Salon pour les suggestions')
                        .addChannelTypes(ChannelType.GuildText)
                        .setRequired(true)
                )
        )
        .addSubcommand(subcommand =>
            subcommand
                .setName('secure')
                .setDescription('Configure la sécurité anti-spam et insultes')
                .addBooleanOption(option =>
                    option.setName('activer')
                        .setDescription('Activer la sécurité')
                        .setRequired(true)
                )
                .addChannelOption(option =>
                    option.setName('salon')
                        .setDescription('Salon à protéger')
                        .addChannelTypes(ChannelType.GuildText)
                        .setRequired(false)
                )
        )
        .addSubcommand(subcommand =>
            subcommand
                .setName('convanalys')
                .setDescription('Active l\'analyse des conversations par Claude')
                .addBooleanOption(option =>
                    option.setName('activer')
                        .setDescription('Activer l\'analyse')
                        .setRequired(true)
                )
                .addChannelOption(option =>
                    option.setName('salon')
                        .setDescription('Salon à analyser')
                        .addChannelTypes(ChannelType.GuildText)
                        .setRequired(false)
                )
        )
        .addSubcommand(subcommand =>
            subcommand
                .setName('view')
                .setDescription('Voir la configuration actuelle')
        ),
    
    async execute(interaction) {
        if (!interaction.member.permissions.has(PermissionFlagsBits.Administrator)) {
            return interaction.reply({ 
                content: '❌ Tu dois être administrateur pour utiliser cette commande!', 
                ephemeral: true 
            });
        }

        const subcommand = interaction.options.getSubcommand();
        const guildId = interaction.guild.id;
        
        if (!global.guildConfigs.has(guildId)) {
            global.guildConfigs.set(guildId, {});
        }
        
        const guildConfig = global.guildConfigs.get(guildId);

        switch (subcommand) {
            case 'suggestion':
                const suggestionChannel = interaction.options.getChannel('salon');
                guildConfig.suggestionChannel = suggestionChannel.id;
                global.guildConfigs.set(guildId, guildConfig);
                
                await interaction.reply({
                    content: `✅ Salon des suggestions configuré sur ${suggestionChannel}!`,
                    ephemeral: true
                });
                break;

            case 'secure':
                const secureEnabled = interaction.options.getBoolean('activer');
                const secureChannel = interaction.options.getChannel('salon');
                
                guildConfig.securityEnabled = secureEnabled;
                if (secureChannel) {
                    if (!guildConfig.secureChannels) guildConfig.secureChannels = [];
                    if (!guildConfig.secureChannels.includes(secureChannel.id)) {
                        guildConfig.secureChannels.push(secureChannel.id);
                    }
                }
                global.guildConfigs.set(guildId, guildConfig);
                
                await interaction.reply({
                    content: `✅ Sécurité ${secureEnabled ? 'activée' : 'désactivée'}${secureChannel ? ` pour ${secureChannel}` : ''}!`,
                    ephemeral: true
                });
                break;

            case 'convanalys':
                const analysEnabled = interaction.options.getBoolean('activer');
                const analysChannel = interaction.options.getChannel('salon');
                
                guildConfig.conversationAnalysis = analysEnabled;
                if (analysChannel) {
                    if (!guildConfig.analysisChannels) guildConfig.analysisChannels = [];
                    if (!guildConfig.analysisChannels.includes(analysChannel.id)) {
                        guildConfig.analysisChannels.push(analysChannel.id);
                    }
                }
                global.guildConfigs.set(guildId, guildConfig);
                
                await interaction.reply({
                    content: `✅ Analyse des conversations ${analysEnabled ? 'activée' : 'désactivée'}${analysChannel ? ` pour ${analysChannel}` : ''}!`,
                    ephemeral: true
                });
                break;

            case 'view':
                const embed = new EmbedBuilder()
                    .setColor('#0099FF')
                    .setTitle('⚙️ Configuration du serveur')
                    .addFields(
                        { 
                            name: '💡 Salon suggestions', 
                            value: guildConfig.suggestionChannel ? 
                                `<#${guildConfig.suggestionChannel}>` : 'Non configuré', 
                            inline: true 
                        },
                        { 
                            name: '🛡️ Sécurité', 
                            value: guildConfig.securityEnabled ? '✅ Activée' : '❌ Désactivée', 
                            inline: true 
                        },
                        { 
                            name: '🔍 Analyse conversations', 
                            value: guildConfig.conversationAnalysis ? '✅ Activée' : '❌ Désactivée', 
                            inline: true 
                        }
                    )
                    .setFooter({ text: 'Peerkinton • Configuration' })
                    .setTimestamp();

                if (guildConfig.secureChannels && guildConfig.secureChannels.length > 0) {
                    embed.addFields({
                        name: '🔒 Salons sécurisés',
                        value: guildConfig.secureChannels.map(id => `<#${id}>`).join(', '),
                        inline: false
                    });
                }

                if (guildConfig.analysisChannels && guildConfig.analysisChannels.length > 0) {
                    embed.addFields({
                        name: '📊 Salons analysés',
                        value: guildConfig.analysisChannels.map(id => `<#${id}>`).join(', '),
                        inline: false
                    });
                }

                await interaction.reply({ embeds: [embed], ephemeral: true });
                break;
        }
    }
};