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

module.exports = {
    category: 'xp',
    data: new SlashCommandBuilder()
        .setName('bumptime')
        .setDescription('Vérifier le dernier bump et le temps restant avant le prochain'),
    async execute(interaction) {
        await interaction.deferReply({ flags: MessageFlags.Ephemeral });
        
        try {
            const [bumps] = await db.query(
                'SELECT * FROM bumps WHERE guildId = ? ORDER BY bumpTime DESC LIMIT 1',
                [interaction.guild.id]
            );
            
            if (bumps.length === 0) {
                return interaction.editReply({
                    content: '❌ Aucun bump enregistré pour ce serveur.'
                });
            }
            
            const lastBump = bumps[0];
            const bumpTime = parseInt(lastBump.bumpTime, 10);
            const now = Date.now();
            const timeSinceBump = now - bumpTime;
            const twoHours = 2 * 60 * 60 * 1000;
            const timeUntilNextBump = twoHours - timeSinceBump;
            
            const user = await interaction.client.users.fetch(lastBump.userId).catch(() => null);
            const userTag = user ? user.tag : `ID: ${lastBump.userId}`;
            
            const embed = new EmbedBuilder()
                .setAuthor({ 
                    name: interaction.guild.name, 
                    iconURL: interaction.guild.iconURL({ dynamic: true }) || undefined 
                })
                .setTimestamp();
            
            if (timeUntilNextBump > 0) {
                const hours = Math.floor(timeUntilNextBump / (60 * 60 * 1000));
                const minutes = Math.floor((timeUntilNextBump % (60 * 60 * 1000)) / (60 * 1000));
                const seconds = Math.floor((timeUntilNextBump % (60 * 1000)) / 1000);
                
                embed.setTitle('⏳ Bump en Cooldown')
                    .setColor(colors.warning)
                    .setDescription(`Le dernier bump a été effectué il y a moins de 2 heures.`)
                    .addFields(
                        { name: '👤 Dernier bump par', value: `\`${userTag}\``, inline: true },
                        { name: '⏰ Il y a', value: `\`${Math.floor(timeSinceBump / (60 * 60 * 1000))}h ${Math.floor((timeSinceBump % (60 * 60 * 1000)) / (60 * 1000))}m\``, inline: true },
                        { name: '🕐 Temps restant', value: `\`${hours}h ${minutes}m ${seconds}s\``, inline: true },
                        { name: '📅 Prochain bump disponible', value: `<t:${Math.floor((bumpTime + twoHours) / 1000)}:R>`, inline: false }
                    )
                    .setFooter({ text: 'Utilise /bump (Disboard) pour bump le serveur' });
            } else {
                embed.setTitle(`${emojis.success} Bump Disponible`)
                    .setColor(colors.success)
                    .setDescription(`**Le serveur peut être bumpé maintenant !**`)
                    .addFields(
                        { name: '👤 Dernier bump par', value: `\`${userTag}\``, inline: true },
                        { name: '⏰ Il y a', value: `\`${Math.floor(timeSinceBump / (60 * 60 * 1000))}h ${Math.floor((timeSinceBump % (60 * 60 * 1000)) / (60 * 1000))}m\``, inline: true },
                        { name: '✅ Statut', value: '**Disponible**', inline: true },
                        { name: '💡 Astuce', value: 'Utilise `/bump` (Disboard) pour bump le serveur !', inline: false }
                    )
                    .setFooter({ text: 'Utilise /bump (Disboard) pour bump le serveur' });
            }
            
            await interaction.editReply({ embeds: [embed] });
            
        } catch (err) {
            console.error('Erreur bumptime:', err);
            await interaction.editReply({
                content: '❌ Erreur lors de la vérification du bump.'
            });
        }
    },
};