/**
 * /profil — Look up a player's stats.
 * Can search by @mention (Discord user) or in-game username.
 */

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

const RANK_EMOJI = {
    Bronze:   '🟫',
    Silver:   '⬜',
    Gold:     '🟨',
    Platinum: '💎',
    Diamond:  '💠',
    Legend:   '👑',
};

export const data = new SlashCommandBuilder()
    .setName('profil')
    .setDescription('Lihat statistik pemain PES League')
    .addUserOption(opt =>
        opt.setName('user')
           .setDescription('Tag pengguna Discord (@mention)')
           .setRequired(false)
    )
    .addStringOption(opt =>
        opt.setName('username')
           .setDescription('Username in-game')
           .setRequired(false)
    );

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

    const mentionedUser = interaction.options.getUser('user');
    const username      = interaction.options.getString('username');

    // If nothing provided, look up the command author
    const targetDiscordId = mentionedUser
        ? mentionedUser.id
        : (!username ? interaction.user.id : null);

    try {
        const player = targetDiscordId
            ? await findPlayerByDiscordId(targetDiscordId)
            : await findPlayerByUsername(username);

        const total   = (player.wins ?? 0) + (player.losses ?? 0) + (player.draws ?? 0);
        const winRate = total > 0 ? ((player.wins / total) * 100).toFixed(1) : '0.0';
        const rankEmoji = RANK_EMOJI[player.rank] ?? '🎮';

        const embed = new EmbedBuilder()
            .setColor(0x1d4ed8)
            .setTitle(`${rankEmoji} ${player.username}`)
            .setDescription(`**Rank:** ${player.rank}  •  **ELO:** ${player.elo}`)
            .addFields(
                { name: '✅ Menang',  value: String(player.wins   ?? 0), inline: true },
                { name: '❌ Kalah',   value: String(player.losses ?? 0), inline: true },
                { name: '🤝 Seri',    value: String(player.draws  ?? 0), inline: true },
                { name: '📊 Win Rate', value: `${winRate}%`,              inline: true },
                { name: '🎮 Total',   value: String(total),              inline: true },
            )
            .setTimestamp()
            .setFooter({ text: `Player ID #${player.id}` });

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