import { Events } from 'discord.js';
import { handleTicketButton } from '../modules/ticket/buttons.js';
import { handleStoreInteraction } from '../modules/store/buttons.js';
import { audit } from '../core/db.js';

export default {
  name: Events.InteractionCreate,
  async execute(interaction, client) {
    try {
      if (interaction.isChatInputCommand()) {
        const cmd = client.commands.get(interaction.commandName);
        if (!cmd) return;
        await cmd.execute(interaction, client);
        audit(interaction.guildId, interaction.user.id, `cmd:${interaction.commandName}`);
        return;
      }
      if (interaction.isButton() || interaction.isStringSelectMenu() || interaction.isModalSubmit()) {
        const id = interaction.customId || '';
        if (id.startsWith('ticket_') || id.startsWith('order_')) return handleTicketButton(interaction, client);
        if (id.startsWith('store_')) return handleStoreInteraction(interaction, client);
        if (id.startsWith('clone_')) {
          const { handleCloneInteraction } = await import('../modules/server-clone/interactions.js');
          return handleCloneInteraction(interaction, client);
        }
        if (id.startsWith('setup_')) {
          const { handleSetupInteraction } = await import('../modules/setup-wizard/interactions.js');
          return handleSetupInteraction(interaction, client);
        }
      }
    } catch (e) {
      console.error('[interaction]', e);
      if (interaction.isRepliable()) {
        const msg = `❌ Error: ${e.message}`;
        if (interaction.replied || interaction.deferred) {
          await interaction.followUp({ content: msg, ephemeral: true }).catch(() => {});
        } else {
          await interaction.reply({ content: msg, ephemeral: true }).catch(() => {});
        }
      }
    }
  },
};
