const chalk = require('chalk');
const { Client, GatewayIntentBits, Collection } = require('discord.js');
const { Player } = require('discord-player');
const fs = require('node:fs');
const path = require('node:path');
const dotenv = require('dotenv');
const express = require('express');

const createEmbed = require('./functions/createEmbed.js');
dotenv.config();

const log = {
  Info: (message) => console.log(chalk.blue('INFO'), message),
  Error: (message) => console.log(chalk.red('ERROR'), message),
  Warn: (message) => console.log(chalk.hex('#FFA500'), message),
};

// Register client and music events
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
client.player = new Player(client);

require('./functions/player.js').registerEvents({ client, createEmbed });


// Express
const app = express();
app.use(express.json());

const minecraftRoute = require('./routes/Minecraft');
const userRoute = require('./routes/User');
const teamRoute = require('./routes/Team');

app.use('/minecraft', minecraftRoute);
app.use('/user', userRoute);
app.use('/team', teamRoute);

app.listen('4000', () => {
  log.Info('Express app running');
});


// Command handling
client.commands = new Collection();

const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
  const filePath = path.join(commandsPath, file);
  const command = require(filePath);

  if ('data' in command && 'execute' in command) {
    client.commands.set(command.data.name, command);
  } else {
    log.Warn(`The command at ${filePath} is missing a required "data" or "execute" property.`);
  }
}


// Event handling
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));

for (const file of eventFiles) {
  const filePath = path.join(eventsPath, file);
  const event = require(filePath);
  if (event.once) {
    client.once(event.name, (...args) => event.execute({ client, log, createEmbed }, ...args));
  } else {
    client.on(event.name, (...args) => event.execute({ client, log, createEmbed }, ...args));
  }
}

client.login(process.env.DISCORD_TOKEN);

module.exports.client = client;
