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

const configPath = path.join(__dirname, 'data/config.json');

function loadConfig() {
    if (fs.existsSync(configPath)) {
        return JSON.parse(fs.readFileSync(configPath, 'utf8'));
    }
    return {};
}

const config = loadConfig();
const token = config.discord_token;
const guildId = config.guild_id;

if (!token) {
    console.error('No Discord Token found in data/config.json');
    process.exit(1);
}

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

const player = createAudioPlayer();

client.on('ready', async () => {
    console.log(`Logged in as ${client.user.tag}`);
    
    // Register commands
    const commands = [
        new SlashCommandBuilder()
            .setName('testsahur')
            .setDescription('Memutar file audio sahur')
    ].map(command => command.toJSON());

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

    // Auto-reconnect to last voice channel
    const lastVoice = config.last_voice_channel;
    if (lastVoice && lastVoice.guildId && lastVoice.channelId) {
        joinVC(lastVoice.guildId, lastVoice.channelId);
    }
});

function joinVC(gId, cId) {
    const connection = joinVoiceChannel({
        channelId: cId,
        guildId: gId,
        adapterCreator: client.guilds.cache.get(gId).voiceAdapterCreator,
        selfDeaf: false,
    });

    connection.on(VoiceConnectionStatus.Disconnected, async () => {
        try {
            await Promise.race([
                entersState(connection, VoiceConnectionStatus.Signalling, 5_000),
                entersState(connection, VoiceConnectionStatus.Connecting, 5_000),
            ]);
        } catch (error) {
            console.log('Connection lost, attempting to reconnect...');
            setTimeout(() => joinVC(gId, cId), 5000);
        }
    });

    connection.subscribe(player);
}

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

    if (interaction.commandName === 'testsahur') {
        const member = interaction.member;
        if (!member.voice.channel) {
            return interaction.reply('Kamu harus berada di Voice Channel!');
        }

        const channel = member.voice.channel;
        const gId = interaction.guildId;
        const cId = channel.id;

        // Save last channel
        config.last_voice_channel = { guildId: gId, channelId: cId };
        fs.writeFileSync(configPath, JSON.stringify(config, null, 2));

        joinVC(gId, cId);

        const resource = createAudioResource(path.join(__dirname, 'assets/audio/sahur.mp3'));
        player.play(resource);

        await interaction.reply('🔊 Memutar audio Sahur!');
    }
});

client.login(token);
