const { Events, EmbedBuilder } = require('discord.js');
const db = require('../functions/database/db.js');
const { addXP, isChannelExcluded, getUserXP, getXPMultiplier, getXPProgress } = require('../functions/xp/xp.js');
const { colors } = require('../utils/constants');

// --- FONCTIONS UTILITAIRES ---

async function detectBump(message) {
    const bumpBots = ['302050872383242240']; // Disboard bot ID
    if (!message.author.bot || !bumpBots.includes(message.author.id)) return null;

    const content = message.content?.toLowerCase() || '';
    const embed = message.embeds[0];
    if (!embed) return null;

    const embedDescription = embed.description?.toLowerCase() || '';
    const embedTitle = embed.title?.toLowerCase() || '';
    const bumpKeywords = ['bump done', 'bump réussi', 'bump réalisé', 'bump effectué', 'serv bump', 'server bump'];

    const isBumpMessage = bumpKeywords.some(keyword =>
        embedDescription.includes(keyword) ||
        embedTitle.includes(keyword) ||
        content.includes(keyword)
    );

    if (!isBumpMessage) return null;

    // Tentative de récupération de l'ID utilisateur
    if (message.mentions.users.size > 0) return message.mentions.users.first().id;

    const userIdMatch = embedDescription.match(/<@!?(\d+)>/);
    if (userIdMatch) return userIdMatch[1];

    if (embed.footer) {
        const footerMatch = embed.footer.text?.match(/<@!?(\d+)>/);
        if (footerMatch) return footerMatch[1];
    }

    return null;
}

function detectWelcomeMessage(message) {
    if (message.author.bot) return false;
    const welcomeKeywords = ['bienvenue', 'welcome', 'bvn', 'salut', 'hey', 'bonjour'];
    const content = message.content.toLowerCase();
    
    return welcomeKeywords.some(k => content.includes(k)) && 
           message.mentions.users.size > 0 && 
           message.content.length < 100;
}

async function handleLevelUp(message, result, member) {
    if (!result || !result.levelUp) return;

    const progress = getXPProgress(result.newXP, result.newLevel);
    const embed = new EmbedBuilder()
        .setTitle('🎉 Level Up !')
        .setDescription(`Félicitations ${member.toString()} ! Tu as atteint le niveau **${result.newLevel}** !`)
        .setColor(colors.success)
        .addFields(
            { name: '📊 XP', value: `${result.newXP} XP`, inline: true },
            { name: '⭐ Niveau', value: `${result.newLevel}`, inline: true },
            { name: '📈 Progression', value: `${progress.current}/${progress.needed} XP (${progress.percentage}%)`, inline: true }
        )
        .setThumbnail(member.user.displayAvatarURL({ dynamic: true }))
        .setTimestamp();

    await message.channel.send({ embeds: [embed] });
}

// --- LOGIQUE PRINCIPALE ---

module.exports = {
    name: Events.MessageCreate,
    async execute(message) {
        if (!message.channel.isTextBased() || message.channel.isDMBased()) return;

        try {
            // 1. GESTION DES BUMPS
            const bumpedUserId = await detectBump(message);
            if (bumpedUserId) {
                try {
                    await db.query('INSERT INTO bumps (userId, guildId, bumpTime, reminderSent) VALUES (?, ?, ?, ?)', [bumpedUserId, message.guild.id, Date.now(), false]);
                    
                    const member = await message.guild.members.fetch(bumpedUserId).catch(() => null);
                    if (member) {
                        const xpGained = Math.floor(Math.random() * 51) + 50; // 50-100 XP
                        const result = await addXP(bumpedUserId, message.guild.id, xpGained, 'bump', getXPMultiplier(member));
                        await handleLevelUp(message, result, member);
                    }
                } catch (err) { console.error('Erreur bump:', err); }
                return;
            }

            // 2. IGNORER LES BOTS (Sauf pour les bumps traités au-dessus)
            if (message.author.bot) return;

            // 3. GESTION DES TICKETS
            const [tickets] = await db.query('SELECT * FROM tickets WHERE channelId = ? AND status = ?', [message.channel.id, 'Ouvert']);
            if (tickets.length > 0) {
                const ticket = tickets[0];
                const attachments = message.attachments.size > 0 ? message.attachments.map(a => a.url).join(', ') : null;
                
                const maxTag = 100;
                const maxText = 65535;
                const safeUserTag = (message.author.tag && message.author.tag.length > maxTag) ? message.author.tag.substring(0, maxTag) : message.author.tag;
                const safeContent = (message.content && message.content.length > maxText) ? message.content.substring(0, maxText) : message.content;
                const safeAttachments = (attachments && attachments.length > maxText) ? attachments.substring(0, maxText) : attachments;

                await db.query(
                    `INSERT INTO ticket_messages (ticketId, messageId, userId, userTag, content, attachments, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)`,
                    [ticket.ticketId, message.id, message.author.id, safeUserTag, safeContent || null, safeAttachments, message.createdTimestamp]
                );
                return; // Pas d'XP dans les tickets
            }

            // 4. SYSTÈME D'XP (Messages normaux)
            const excluded = await isChannelExcluded(message.channel.id, message.guild.id);
            if (!excluded) {
                const userXP = await getUserXP(message.author.id, message.guild.id);
                const now = Date.now();
                const cooldown = 15000; // 15s
                
                let lastMessageTime = parseInt(userXP.lastMessageTime || 0, 10);
                // Reset si date invalide
                if (lastMessageTime > now || lastMessageTime < (now - 31536000000)) lastMessageTime = 0;

                if (lastMessageTime === 0 || (now - lastMessageTime) >= cooldown) {
                    const member = await message.guild.members.fetch(message.author.id).catch(() => null);
                    const xpGained = Math.floor(Math.random() * 11) + 15; // 15-25 XP
                    
                    const result = await addXP(message.author.id, message.guild.id, xpGained, 'message', member ? getXPMultiplier(member) : 1.0);
                    if (member) await handleLevelUp(message, result, member);

                    // Mise à jour stats + timestamp
                    await db.query('UPDATE user_xp SET lastMessageTime = ?, totalMessages = totalMessages + 1 WHERE userId = ? AND guildId = ?', [now, message.author.id, message.guild.id]);
                } else {
                    // Juste incrémenter le compteur de messages (Cooldown actif)
                    await db.query('UPDATE user_xp SET totalMessages = totalMessages + 1 WHERE userId = ? AND guildId = ?', [message.author.id, message.guild.id]);
                }
            }

            // 5. MESSAGES DE BIENVENUE
            if (detectWelcomeMessage(message)) {
                try {
                    await message.react('👋').catch(() => null);
                    await message.react('🎉').catch(() => null);

                    const member = await message.guild.members.fetch(message.author.id).catch(() => null);
                    if (member) {
                        const xpGained = Math.floor(Math.random() * 21) + 20; // 20-40 XP
                        const result = await addXP(message.author.id, message.guild.id, xpGained, 'welcome', getXPMultiplier(member));
                        await handleLevelUp(message, result, member);
                    }
                } catch (err) { console.error('Erreur bienvenue:', err); }
            }

        } catch (err) {
            console.error('Erreur globale messageCreate:', err);
        }
    },
};