/**
 * /listmatchturnamen — Show pending matches for a specific tournament.
 */

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

export const data = new SlashCommandBuilder()
    .setName('listmatchturnamen')
    .setDescription('Tampilkan pertandingan turnamen yang belum selesai')
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
    .addIntegerOption(opt =>
        opt.setName('tournament_id')
           .setDescription('ID turnamen (lihat dengan /listturnamen)')
           .setRequired(true)
           .setMinValue(1)
    );

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

    const tournamentId = interaction.options.getInteger('tournament_id');

    try {
        const data    = await getTournamentPendingMatches(tournamentId);
        const matches = data.matches ?? [];
        const title   = `Match Turnamen: ${data.tournament?.title ?? '#' + tournamentId}`;

        const embed = pendingMatchesEmbed(matches, title);
        if (matches.length) {
            embed.setFooter({ text: 'Gunakan /skorturnamen <match_id> <skor1> <skor2> untuk input hasil' });
        }

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