const { REST, Routes, SlashCommandBuilder } = require('discord.js');
const fs = require('fs');
const path = require('path');

// Load config
let TOKEN, CLIENT_ID;
try {
    const configPath = path.join(__dirname, 'config.json');
    if (fs.existsSync(configPath)) {
        const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
        TOKEN = config.DISCORD_TOKEN;
        CLIENT_ID = config.DISCORD_CLIENT_ID;
    } else {
        TOKEN = process.env.DISCORD_TOKEN;
        CLIENT_ID = process.env.DISCORD_CLIENT_ID;
    }
} catch (err) {
    console.error('ERROR: config.json is invalid or error reading it.');
    process.exit(1);
}

if (!TOKEN || !CLIENT_ID) {
    console.error('ERROR: DISCORD_TOKEN or DISCORD_CLIENT_ID is missing in config.json.');
    process.exit(1);
}

const commands = [
    new SlashCommandBuilder()
        .setName('join')
        .setDescription('Masuk ke Voice Channel kamu'),
    new SlashCommandBuilder()
        .setName('sahur')
        .setDescription('Masuk ke Voice Channel dan putar alarm sahur'),
].map(command => command.toJSON());

const rest = new REST({ version: '10' }).setToken(TOKEN);

(async () => {
    try {
        console.log(`Started refreshing ${commands.length} application (/) commands.`);

        const data = await rest.put(
            Routes.applicationCommands(CLIENT_ID),
            { body: commands },
        );

        console.log(`Successfully reloaded ${data.length} application (/) commands.`);
    } catch (error) {
        console.error(error);
        process.exit(1);
    }
})();
