require('dotenv').config();
const { 
    Client, 
    GatewayIntentBits, 
    REST, 
    Routes, 
    SlashCommandBuilder 
} = require('discord.js');
const { 
    joinVoiceChannel, 
    createAudioPlayer, 
    createAudioResource, 
    AudioPlayerStatus, 
    NoSubscriberBehavior 
} = require('@discordjs/voice');
const express = require('express');
const fs = require('fs');
const path = require('path');

// --- Configuration ---
const DISCORD_TOKEN = process.env.DISCORD_TOKEN;
const CLIENT_ID = process.env.CLIENT_ID;
const GUILD_ID = process.env.GUILD_ID;

const app = express();
const port = 8080;

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

let player = null;
let connection = null;
let isLooping = false;

// Function to play local sahur.mp3
function playAudio() {
    if (!connection) return;

    const filePath = path.join(__dirname, 'sahur.mp3');
    if (!fs.existsSync(filePath)) {
        console.error('File sahur.mp3 tidak ditemukan!');
        return;
    }

    if (!player) {
        player = createAudioPlayer({
            behaviors: {
                noSubscriber: NoSubscriberBehavior.Play,
            },
        });

        player.on(AudioPlayerStatus.Idle, () => {
            if (isLooping && connection) {
                console.log('Looping: Memutar ulang sahur.mp3');
                playAudio();
            }
        });

        player.on('error', error => {
            console.error('Error Audio Player:', error.message);
        });
    }

    const resource = createAudioResource(filePath);
    player.play(resource);
    connection.subscribe(player);
}

// Slash Commands Definition
const commands = [
    new SlashCommandBuilder()
        .setName('join')
        .setDescription('Membuat bot masuk ke Voice Channel kamu'),
    new SlashCommandBuilder()
        .setName('test_sahur')
        .setDescription('Memutar sahur.mp3 secara berulang (loop)'),
].map(command => command.toJSON());

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

async function registerCommands() {
    try {
        console.log('Refreshing application (/) commands...');
        await rest.put(Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), { body: commands });
        console.log('Commands registered successfully.');
    } catch (error) {
        console.error('Error registering commands:', error);
    }
}

client.on('ready', () => {
    console.log(`Bot Online: ${client.user.tag}`);
    registerCommands();
    
    // Keep-Alive Ping
    setInterval(() => {
        console.log(`[Keep-Alive] Bot still running at ${new Date().toISOString()}`);
    }, 10 * 60 * 1000); // Every 10 minutes
});

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

    if (interaction.commandName === 'join') {
        const voiceChannel = interaction.member.voice.channel;
        if (!voiceChannel) {
            return interaction.reply({ content: 'Kamu harus berada di Voice Channel!', ephemeral: true });
        }

        connection = joinVoiceChannel({
            channelId: voiceChannel.id,
            guildId: interaction.guild.id,
            adapterCreator: interaction.guild.voiceAdapterCreator,
        });

        await interaction.reply(`Berhasil join ke <#${voiceChannel.id}>`);
    }

    if (interaction.commandName === 'test_sahur') {
        if (!connection) {
            return interaction.reply({ content: 'Gunakan /join terlebih dahulu!', ephemeral: true });
        }

        isLooping = true;
        playAudio();
        await interaction.reply('Memutar sahur.mp3 (Loop aktif 🔁)');
    }
});

// Minimal Keep-Alive Web Server
app.get('/', (req, res) => res.send('Bot Sahur is Alive! 🌙'));
app.listen(port, () => console.log(`Keep-Alive server on port ${port}`));

client.login(DISCORD_TOKEN);
