import DiscordEvent from "../../util/DiscordEvent";
import { DiscordInteractionCommands } from "../../index";
import { Client, Interaction } from "discord.js";

export default class InteractionCreate extends DiscordEvent {
  constructor(client: Client) {
    super("interactionCreate", client);
  }

  public async execute(interaction: Interaction): Promise<void> {
    if (!interaction.isChatInputCommand()) return;
    const command = DiscordInteractionCommands.get(interaction.commandName);
    if (!command) return console.error(`No command matching ${interaction.commandName} was found.`);
    try {
      await command.execute(interaction);
      console.info(
        `[Info - Discord] Command '${interaction.commandName}' executed by '${interaction.user.username}'`
      );
    } catch (error) {
      console.error(
        `Error executing command '${interaction.commandName}': by '${interaction.user.username}'\n${error}`
      );
      if (interaction.replied || interaction.deferred) {
        await interaction.followUp({
          content: "There was an error while executing this command!",
          ephemeral: true,
        });
      } else {
        await interaction.reply({
          content: "There was an error while executing this command!",
          ephemeral: true,
        });
      }
    }
  }
}