/**
 * /listturnamen — Show active tournaments.
 */

import { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder } from 'discord.js';
import { getTournaments } from '../api.js';
import { errorEmbed } from '../embeds.js';

export const data = new SlashCommandBuilder()
    .setName('listturnamen')
    .setDescription('Tampilkan turnamen yang sedang aktif')
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild);

export async function execute(interaction) {
    await interaction.deferReply({ ephemeral: true });

    try {
        const { tournaments } = await getTournaments();

        const embed = new EmbedBuilder()
            .setColor(0x7c3aed)
            .setTitle('🏆 Turnamen Aktif')
            .setTimestamp();

        if (!tournaments.length) {
            embed.setDescription('Tidak ada turnamen aktif saat ini.');
        } else {
            const lines = tournaments.map((t, i) =>
                `\`${String(i + 1).padStart(2)}\` **#${t.id}** — ${t.title}  \`${t.status}\`  (${t.players_count}/${t.max_players} pemain)`
            );
            embed.setDescription(lines.join('\n'));
            embed.setFooter({ text: 'Gunakan /listmatchturnamen <id> untuk lihat match' });
        }

        await interaction.editReply({ embeds: [embed] });
    } catch (err) {
        await interaction.editReply({ embeds: [errorEmbed(err.message)] });
    }
}
