/**
 * /skorturnamen — Submit score for a tournament match.
 *
 * Usage:
 *   /skorturnamen match_id:<id> skor1:<0-99> skor2:<0-99>
 *
 * Run /listturnamen first to see active tournaments,
 * then /listmatchturnamen <tournament_id> to see pending matches.
 */

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

export const data = new SlashCommandBuilder()
    .setName('skorturnamen')
    .setDescription('Input skor pertandingan turnamen')
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
    .addIntegerOption(opt =>
        opt.setName('match_id')
           .setDescription('ID match turnamen (lihat dengan /listmatchturnamen)')
           .setRequired(true)
           .setMinValue(1)
    )
    .addIntegerOption(opt =>
        opt.setName('skor1')
           .setDescription('Skor Player 1')
           .setRequired(true)
           .setMinValue(0)
           .setMaxValue(99)
    )
    .addIntegerOption(opt =>
        opt.setName('skor2')
           .setDescription('Skor Player 2')
           .setRequired(true)
           .setMinValue(0)
           .setMaxValue(99)
    );

export async function execute(interaction) {
    await interaction.deferReply();

    const matchId = interaction.options.getInteger('match_id');
    const score1  = interaction.options.getInteger('skor1');
    const score2  = interaction.options.getInteger('skor2');

    try {
        const result = await submitTournamentScore(matchId, score1, score2);
        const embed  = tournamentResultEmbed(result);

        await interaction.editReply({ embeds: [embed] });

        // Post to results channel
        const channelId = process.env.RESULTS_CHANNEL_ID;
        if (channelId && channelId !== interaction.channelId) {
            const channel = interaction.client.channels.cache.get(channelId);
            if (channel?.isTextBased()) {
                channel.send({ embeds: [embed] }).catch(() => {});
            }
        }
    } catch (err) {
        await interaction.editReply({ embeds: [errorEmbed(err.message)] });
    }
}
