/**
 * /skor — Submit score for a ranked match.
 *
 * Usage:
 *   /skor match_id:<id> host:<0-99> guest:<0-99>
 */

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

export const data = new SlashCommandBuilder()
    .setName('skor')
    .setDescription('Input skor pertandingan ranked')
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)  // admin/mod only
    .addIntegerOption(opt =>
        opt.setName('match_id')
           .setDescription('ID pertandingan (lihat dengan /listskor)')
           .setRequired(true)
           .setMinValue(1)
    )
    .addIntegerOption(opt =>
        opt.setName('host')
           .setDescription('Skor Host (pemain yang membuat room)')
           .setRequired(true)
           .setMinValue(0)
           .setMaxValue(99)
    )
    .addIntegerOption(opt =>
        opt.setName('guest')
           .setDescription('Skor Guest (pemain yang join)')
           .setRequired(true)
           .setMinValue(0)
           .setMaxValue(99)
    );

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

    const matchId    = interaction.options.getInteger('match_id');
    const scoreHost  = interaction.options.getInteger('host');
    const scoreGuest = interaction.options.getInteger('guest');

    try {
        const result = await submitMatchScore(matchId, scoreHost, scoreGuest);
        const embed  = matchResultEmbed(result);

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

        // Optionally 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)] });
    }
}
