const { REST, Routes } = require('discord.js');
const fs = require('node:fs');
const path = require('node:path');
const logger = require('./src/utils/logger'); // Assuming logger is setup
require('dotenv').config(); // Load .env variables

console.log('CLIENT_ID: ', process.env.CLIENT_ID ? 'Present' : process.env.CLIENT_ID);
console.log('DISCORD_TOKEN:', process.env.DISCORD_TOKEN ? 'Present' : process.env.DISCORD_TOKEN);

// --- Configuration ---
const clientId = process.env.CLIENT_ID;
const token = process.env.DISCORD_TOKEN;
// const guildId = process.env.GUILD_ID; // Uncomment for guild-specific commands during testing

if (!clientId || !token) {
    logger.error('Missing CLIENT_ID or DISCORD_TOKEN in .env file for command deployment!');
    process.exit(1);
}

const commands = [];
// Grab all the command files from the commands directory you created earlier
const commandsPath = path.join(__dirname, 'src', 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
logger.info(`Started loading ${commandFiles.length} application (/) commands for deployment.`);
for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    try {
        const command = require(filePath);
        if ('data' in command && 'execute' in command) {
            commands.push(command.data.toJSON());
            logger.info(`Loaded command: ${command.data.name}`);
        } else {
            logger.warn(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
        }
    } catch (error) {
         logger.error(`Error loading command at ${filePath} for deployment: ${error.message}`, error);
    }
}

// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(token);

// and deploy your commands!
(async () => {
    try {
        logger.info(`Started wiping all global and guild application (/) commands.`);

        // 1. Wipe Global Commands
        await rest.put(
            Routes.applicationCommands(clientId),
            { body: [] }
        );
        logger.info('Successfully wiped all global application commands.');

        // 2. Wipe Guild Commands (optional but recommended for dev/testing guilds)
        const guildId = process.env.GUILD_ID; // Make sure this is set
        if (guildId) {
            await rest.put(
                Routes.applicationGuildCommands(clientId, guildId),
                { body: [] }
            );
            logger.info(`Successfully wiped all application commands in guild ${guildId}.`);
        } else {
            logger.warn('GUILD_ID not set; skipping guild command wipe.');
        }

        // 3. Register New Global Commands
        logger.info(`Registering ${commands.length} new global commands...`);
        const data = await rest.put(
            Routes.applicationCommands(clientId),
            { body: commands },
        );

        logger.info(`Successfully registered ${data.length} new global commands.`);

    } catch (error) {
        logger.error('Failed during command reset and deployment:', error);
    }
})();

