const { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder } = require('discord.js');
const db = require('../../functions/database/db.js'); // instance mysql2/promise

const SPECIAL_BAN_GIFS = {
    '256543419252342785': 'https://cdn.discordapp.com/attachments/1280667750213091399/1294481799682199613/Darkgif-ezgif.com-video-to-gif-converter.gif?ex=68f4f0df&is=68f39f5f&hm=4521788383420117fa71419934bb331e269636028088894ffdbc90be302adaa1&'
};

module.exports = {
    category: 'moderation',
    data: new SlashCommandBuilder()
        .setName('ban')
        .setDescription('Select a member and ban them.')
        .addUserOption(option =>
            option.setName('target')
                .setDescription('The member to ban')
                .setRequired(true))
        .addStringOption(option =>
            option.setName('reason')
                .setDescription('Reason')
                .setRequired(false))
        .addStringOption(option =>
            option.setName('duration')
                .setDescription('Ban duration (ex: 1h, 2d, leave empty for permanent)')
                .setRequired(false))
        .setDefaultMemberPermissions(PermissionFlagsBits.BanMembers),

    async execute(interaction) {
        const target = interaction.options.getUser('target');
        const reason = interaction.options.getString('reason') || 'No reason provided';
        const durationInput = interaction.options.getString('duration');

        await interaction.deferReply()

        if (!target) return interaction.editReply({ content: 'No user specified!' });
        await interaction.guild.bans.create(target.id, { reason: `Banned by ${interaction.user.tag}: ${reason}` });

        let type = 'Permanent';
        let unbanDate = null;

        if (durationInput) {
            const regex = /^(\d+)(s|m|h|d|mo|y)$/;
            const match = durationInput.match(regex);
            if (match) {
                const value = parseInt(match[1]);
                const unit = match[2];
                let multiplier = 1000;
                if (unit === 's') multiplier *= 60 / 60;
                if (unit === 'm') multiplier *= 60;
                if (unit === 'h') multiplier *= 60 * 60;
                if (unit === 'd') multiplier *= 60 * 60 * 24;
                if (unit === 'mo') multiplier *= 60 * 60 * 24 * 30;
                if (unit === 'y') multiplier *= 60 * 60 * 24 * 365;
                unbanDate = Date.now() + value * multiplier;
                type = 'Temporary';
            }
        }
// juste avant la création de l'embed
        let durationText = type;
        if (type === 'Temporary' && unbanDate) {
            const initialDurationMs = unbanDate - Date.now() + (Date.now() - Date.now()); // ça reste l'unbanDate - timestamp original
            function formatInitialDuration(ms) {
                const seconds = Math.floor(ms / 1000) % 60;
                const minutes = Math.floor(ms / (1000 * 60)) % 60;
                const hours = Math.floor(ms / (1000 * 60 * 60)) % 24;
                const days = Math.floor(ms / (1000 * 60 * 60 * 24));
                const months = Math.floor(ms / (1000 * 60 * 60 * 24 * 30));
                const years = Math.floor(ms / (1000 * 60 * 60 * 24 * 365));

                if (years) return `${years} Année${years > 1 ? 's' : ''}`;
                if (months) return `${months} Mois`;
                if (days) return `${days} Jour${days > 1 ? 's' : ''}`;
                if (hours) return `${hours} Heure${hours > 1 ? 's' : ''}`;
                if (minutes) return `${minutes} Minute${minutes > 1 ? 's' : ''}`;
                if (seconds) return `${seconds} Seconde${seconds > 1 ? 's' : ''}`;
                return 'Instantané';
            }

            durationText = formatInitialDuration(initialDurationMs);
        }

        try {
            // Bannissement
            interaction.guild.bans.create(target.id, { reason: `Banned by ${interaction.user.tag}: ${reason}` });

            // Stockage dans MySQL (bans)
            await db.query(
                `INSERT INTO bans (userId, reason, modId, timestamp, type, unbanDate, guildId)
                 VALUES (?, ?, ?, ?, ?, ?, ?)
                     ON DUPLICATE KEY UPDATE reason=VALUES(reason), modId=VALUES(modId), timestamp=VALUES(timestamp), type=VALUES(type), unbanDate=VALUES(unbanDate)`,
                [target.id, reason, interaction.user.id, Date.now(), type, unbanDate, interaction.guild.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, 'Bannissement', reason, type, interaction.guild.id, Date.now()]
            );

            await interaction.editReply(`✅ Successfully banned ${target.tag} (${type})`);

            // Embed log
            const logChannel = interaction.guild.channels.cache.find(ch => ch.name === 'logs');
            if (logChannel) {
                const embed = new EmbedBuilder()
                    .setTitle('User Banned')
                    .setColor('Red')
                    .addFields(
                        { name: 'Banned User', value: `<@${target.id}> (${target.tag})`, inline: true },
                        { name: 'Banned By', value: `<@${interaction.user.id}> (${interaction.user.tag})`, inline: true },
                        { name: 'Reason', value: reason, inline: false },
                        { name: 'Duration', value: durationText, inline: true },
                        { name: 'Date', value: new Date().toLocaleString(), inline: true },
                        { name: 'Guild', value: interaction.guild.name, inline: true }
                    )
                    .setTimestamp();
                let message = '';
                if (SPECIAL_BAN_GIFS[interaction.user.id]) {
                    message = `${SPECIAL_BAN_GIFS[interaction.user.id]}\n (Niku a juste banni quelqu'un)`;
                } else {
                    message = `✅ ${target.tag} a été banni (${type})`;
                }
                await interaction.editReply({ content: message });

                logChannel.send({ embeds: [embed] });
            }

        } catch (err) {
            console.error(err);
            await interaction.editReply({ content: `❌ Failed to ban ${target.tag}` });
        }
    }
};
