// src/bot.js
const { Client, GatewayIntentBits } = require('discord.js');
// src/Bot.js - Update your import statements
const CommandHandler = require('./commands/CommandHandler.js');  // Add .js extension
const PlayerService = require('./services/PlayerService.js');   // Add .js extension
class Bot {
  constructor() {
    this.client = new Client({
      intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
      ],
    });

    this.playerService = new PlayerService();
    this.commandHandler = new CommandHandler(this.playerService);

    this.setupEventHandlers();
  }

  setupEventHandlers() {
    this.client.on('error', this.handleError.bind(this));
    this.client.once('ready', this.handleReady.bind(this));
    this.client.on('interactionCreate', this.handleInteraction.bind(this));
  }

  async start(token) {
    console.log('Starting bot...');
    try {
      await this.client.login(token);
      console.log('Login successful');
    } catch (error) {
      console.error('Login failed:', error);
      throw error;
    }
  }

  handleError(error) {
    console.error('Discord client error:', error);
  }

  handleReady() {
    console.log(`Logged in as ${this.client.user.tag}!`);
  }

  async handleInteraction(interaction) {
    if (!interaction.isCommand()) return;

    try {
      switch (interaction.commandName) {
        case 'ping':
          await this.commandHandler.handlePing(interaction);
          break;
        case 'finduser':
          await this.commandHandler.handleFindUser(interaction);
          break;
        case 'matchhistory':
          await this.commandHandler.handleMatchHistory(interaction);
          break;
        default:
          await interaction.reply({ 
            content: 'Unknown command', 
            ephemeral: true 
          });
      }
    } catch (error) {
      await this.handleCommandError(interaction, error);
    }
  }

  async handleCommandError(interaction, error) {
    console.error('Command error:', error);
    
    if (error.code === 10062) {
      console.log('Interaction expired');
      return;
    }
    
    try {
      const message = 'An error occurred while processing your command.';
      if (interaction.deferred) {
        await interaction.editReply({ content: message, ephemeral: true });
      } else if (!interaction.replied) {
        await interaction.reply({ content: message, ephemeral: true });
      }
    } catch (e) {
      console.error('Error while sending error message:', e);
    }
  }
}

module.exports = Bot;