import { ButtonInteraction } from "discord.js";
import { lootdropService } from "./lootdrop.service";
import { UserError } from "@/lib/errors";
import { getLootdropClaimedMessage } from "./lootdrop.view";

export async function handleLootdropInteraction(interaction: ButtonInteraction) {
    if (interaction.customId === "lootdrop_claim") {
        await interaction.deferReply({ ephemeral: true });

        const result = await lootdropService.tryClaim(interaction.message.id, interaction.user.id, interaction.user.username);

        if (!result.success) {
            throw new UserError(result.error || "Failed to claim.");
        }

        await interaction.editReply({
            content: `🎉 You successfully claimed **${result.amount} ${result.currency}**!`
        });

        const { content, files, components } = await getLootdropClaimedMessage(
            interaction.user.id,
            interaction.user.username,
            interaction.user.displayAvatarURL({ extension: "png" }),
            result.amount || 0,
            result.currency || "Coins"
        );

        await interaction.message.edit({
            content,
            embeds: [],
            files,
            components
        });
    }
}
