/**
 * PES League Discord Bot — entry point
 *
 * Start:  node src/index.js   (or  npm start)
 * Deploy: npm run deploy       (registers slash commands with Discord)
 */

import 'dotenv/config';
import { Client, Collection, Events, GatewayIntentBits } from 'discord.js';
import { readdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

// ── Validate env ──────────────────────────────────────────────────────────────
const required = ['DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'API_URL', 'BOT_SECRET'];
for (const key of required) {
    if (!process.env[key]) {
        console.error(`❌  Missing env var: ${key}`);
        process.exit(1);
    }
}

// ── Discord client ────────────────────────────────────────────────────────────
const client = new Client({
    intents: [GatewayIntentBits.Guilds],
});

// ── Load commands ─────────────────────────────────────────────────────────────
client.commands = new Collection();

const __dirname = dirname(fileURLToPath(import.meta.url));
const commandsPath = join(__dirname, 'commands');
const commandFiles = readdirSync(commandsPath).filter(f => f.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = join(commandsPath, file);
    const command  = await import(filePath);

    if (!command.data || !command.execute) {
        console.warn(`⚠️  Skipping ${file}: missing data or execute export`);
        continue;
    }

    client.commands.set(command.data.name, command);
    console.log(`  ✓ Loaded command: /${command.data.name}`);
}

// ── Events ────────────────────────────────────────────────────────────────────
client.once(Events.ClientReady, (c) => {
    console.log(`\n🤖 PES League Bot ready — logged in as ${c.user.tag}\n`);
});

client.on(Events.InteractionCreate, async (interaction) => {
    if (!interaction.isChatInputCommand()) return;

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

    try {
        await command.execute(interaction);
    } catch (err) {
        console.error(`Error in /${interaction.commandName}:`, err);

        const reply = { content: '❌ Terjadi error saat menjalankan perintah ini.', ephemeral: true };
        if (interaction.deferred || interaction.replied) {
            await interaction.editReply(reply).catch(() => {});
        } else {
            await interaction.reply(reply).catch(() => {});
        }
    }
});

// ── Login ─────────────────────────────────────────────────────────────────────
client.login(process.env.DISCORD_TOKEN);
