const { Events, InteractionType } = require('discord.js');
const logger = require('../utils/logger');

module.exports = {
    name: Events.InteractionCreate,
    async execute(interaction, client) { // Added client parameter
        // Handle only slash commands (ChatInputCommand) for now
        if (!interaction.isChatInputCommand()) return;

        const command = client.commands.get(interaction.commandName);

        if (!command) {
            logger.error(`No command matching ${interaction.commandName} was found.`);
            try {
                await interaction.reply({ content: 'Error: This command was not found!', ephemeral: true });
            } catch (replyError) {
                logger.error(`Failed to send 'command not found' reply: ${replyError.message}`);
            }
            return;
        }

        try {
            // Execute the command's logic
            await command.execute(interaction, client); // Pass client to command execute
            logger.info(`Executed command '${interaction.commandName}' for user ${interaction.user.tag}`);
        } catch (error) {
            logger.error(`Error executing command '${interaction.commandName}': ${error.message}`, error);
            // Try to reply to the interaction, otherwise edit the deferred reply if applicable
            const replyOptions = { content: 'There was an error while executing this command!', ephemeral: true };
            try {
                if (interaction.replied || interaction.deferred) {
                    await interaction.followUp(replyOptions);
                } else {
                    await interaction.reply(replyOptions);
                }
            } catch (replyError) {
                logger.error(`Failed to send error reply for command '${interaction.commandName}': ${replyError.message}`);
            }
        }
    },
};
