process.env.FFMPEG_PATH = require('ffmpeg-static');
const { Client, GatewayIntentBits, SlashCommandBuilder, Routes } = require('discord.js');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, getVoiceConnection, VoiceConnectionStatus } = require('@discordjs/voice');
const { REST } = require('@discordjs/rest');
const { join } = require('path');
const fs = require('fs');

// Load Config
const config = JSON.parse(fs.readFileSync(join(__dirname, 'data/config.json'), 'utf8'));
const token = config.discord_token;

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

const player = createAudioPlayer();

client.on('ready', async () => {
    console.log(`Bot logged in as ${client.user.tag}`);
    
    // Register Commands
    const commands = [
        new SlashCommandBuilder().setName('join').setDescription('Bot masuk ke Voice Channel'),
        new SlashCommandBuilder().setName('testsahur').setDescription('Test audio sahur')
    ].map(cmd => cmd.toJSON());

    const rest = new REST({ version: '10' }).setToken(token);
    try {
        await rest.put(Routes.applicationCommands(client.user.id), { body: commands });
        console.log('Slash commands registered.');
    } catch (err) {
        console.error('Failed to register commands:', err);
    }
});

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

    if (interaction.commandName === 'join') {
        await interaction.deferReply(); // Baris PERTAMA
        console.log('Command dijalankan... /join');

        const channel = interaction.member.voice.channel;
        if (!channel) return interaction.editReply('Masuk ke Voice Channel dulu!');

        // Clean Connection Logic: Cek koneksi yang sudah ada
        let connection = getVoiceConnection(interaction.guildId);
        if (!connection) {
            connection = joinVoiceChannel({
                channelId: channel.id,
                guildId: interaction.guildId,
                adapterCreator: interaction.guild.voiceAdapterCreator,
                selfDeaf: false,
                selfMute: false
            });
            
            // Subscribe player immediately
            connection.subscribe(player);
            
            // Stay 24/7: Pastikan bot tidak disconnect
            connection.on(VoiceConnectionStatus.Disconnected, () => {
                console.log('Bot terputus dari voice channel.');
            });

            await interaction.editReply('Berhasil join ke Voice Channel dan Standby 24/7!');
        } else {
            await interaction.editReply('Bot sudah berada di dalam Voice Channel.');
        }
    }

    if (interaction.commandName === 'testsahur') {
        await interaction.deferReply(); // Baris PERTAMA
        console.log('Command dijalankan... /testsahur');

        const connection = getVoiceConnection(interaction.guildId);
        if (!connection) return interaction.editReply('Bot belum join! Gunakan /join dulu.');

        try {
            // Audio Fix as requested with Volume Booster
            const resource = createAudioResource(join(__dirname, 'assets', 'audio', 'sahur.mp3'), { inlineVolume: true });
            resource.volume.setVolume(1.0);
            
            connection.subscribe(player);
            player.play(resource);

            // Edit Reply as requested
            await interaction.editReply('Memutar audio sahur... 🔊');
        } catch (error) {
            console.error('Error playing audio:', error);
            await interaction.editReply('Gagal memutar audio. Pastikan file sahur.mp3 ada di folder assets/audio/');
        }
    }
});

client.login(token);
