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

module.exports = {
    category: 'moderation',
    data: new SlashCommandBuilder()
        .setName('ban')
        .setDescription('Bannir un membre du serveur.')
        .addUserOption(option =>
            option.setName('target')
                .setDescription('Le membre à bannir')
                .setRequired(true))
        .addStringOption(option =>
            option.setName('reason')
                .setDescription('Raison du bannissement')
                .setRequired(false))
        .addStringOption(option =>
            option.setName('duration')
                .setDescription('Durée du ban (ex: 1h, 2d, laisser vide pour permanent)')
                .setRequired(false))
        .setDefaultMemberPermissions(PermissionFlagsBits.BanMembers),

    async execute(interaction) {
        const target = interaction.options.getUser('target');
        const reason = interaction.options.getString('reason') || 'Aucune raison fournie';
        const durationInput = interaction.options.getString('duration');

        await interaction.deferReply({ flags: MessageFlags.Ephemeral });

        if (!target) return interaction.editReply({ content: '❌ Aucun utilisateur spécifié !' });

        const member = await interaction.guild.members.fetch(target.id).catch(() => null);
        if (member) {
            if (member.roles.highest.position >= interaction.member.roles.highest.position && interaction.guild.ownerId !== interaction.user.id) {
                return interaction.editReply({ content: '❌ Tu ne peux pas bannir cet utilisateur car il a un rôle supérieur ou égal au tien.' });
            }
            if (member.id === interaction.guild.ownerId) {
                return interaction.editReply({ content: '❌ Tu ne peux pas bannir le propriétaire du serveur.' });
            }
            if (!member.bannable) {
                return interaction.editReply({ content: '❌ Je ne peux pas bannir cet utilisateur (rôle supérieur au mien ?).' });
            }
        }

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

        if (durationInput) {
            const durationMs = parseDuration(durationInput);
            if (durationMs) {
                unbanDate = Date.now() + durationMs;
                type = 'Temporary';
                durationText = formatDuration(durationMs);
            } else {
                return interaction.editReply({ content: '❌ Format de durée invalide (ex: 1h, 2d).' });
            }
        }

        try {
            await interaction.guild.bans.create(target.id, { reason: `Banni par ${interaction.user.tag}: ${reason}` });

            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()]
            );

            const embed = new EmbedBuilder()
                .setAuthor({ name: target.displayName, iconURL: target.displayAvatarURL({ dynamic: true }) })
                .setTitle(`${emojis.ban} Utilisateur Banni`)
                .setColor(colors.ban)
                .setThumbnail(target.displayAvatarURL({ dynamic: true }))
                .setDescription(`${target.toString()} a été banni du serveur.`)
                .addFields(
                    { name: '👤 Utilisateur', value: `${target.toString()}\n\`${target.tag}\``, inline: true },
                    { name: '👮 Modérateur', value: `${interaction.user.toString()}\n\`${interaction.user.tag}\``, inline: true },
                    { name: '⏱️ Durée', value: `\`${durationText}\``, inline: true },
                    { name: '📝 Raison', value: reason, inline: false },
                    { name: '📅 Date', value: `<t:${Math.floor(Date.now() / 1000)}:F>`, inline: true },
                    { name: '🏷️ Type', value: `\`${type}\``, inline: true }
                )
                .setFooter({ text: `ID: ${target.id} • ${interaction.guild.name}` })
                .setTimestamp();

            await interaction.editReply({ embeds: [embed] });

            const logEmbed = new EmbedBuilder()
                .setAuthor({ name: interaction.user.displayName, iconURL: interaction.user.displayAvatarURL({ dynamic: true }) })
                .setTitle(`${emojis.ban} Bannissement`)
                .setColor(colors.ban)
                .setThumbnail(target.displayAvatarURL({ dynamic: true }))
                .setDescription(`${target.toString()} a été banni du serveur.`)
                .addFields(
                    { name: '👤 Utilisateur', value: `${target.toString()}\n\`${target.tag}\``, inline: true },
                    { name: '👮 Modérateur', value: `${interaction.user.toString()}\n\`${interaction.user.tag}\``, inline: true },
                    { name: '⏱️ Durée', value: `\`${durationText}\``, inline: true },
                    { name: '📝 Raison', value: reason, inline: false }
                )
                .setFooter({ text: `ID: ${target.id} • ${interaction.guild.name}` })
                .setTimestamp();
            
            await sendLog(interaction.guild, { embeds: [logEmbed] });

        } catch (err) {
            console.error('Erreur ban:', err);
            await interaction.editReply({ content: `❌ Erreur: ${err.message}` });
        }
    },
};