import { ButtonInteraction, MessageFlags } from "discord.js"; import { inventoryService } from "@/modules/inventory/inventory.service"; import { userService } from "@/modules/user/user.service"; import { UserError } from "@/lib/errors"; export async function handleShopInteraction(interaction: ButtonInteraction) { if (!interaction.customId.startsWith("shop_buy_")) return; await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const itemId = parseInt(interaction.customId.replace("shop_buy_", "")); if (isNaN(itemId)) { throw new UserError("Invalid Item ID."); } const item = await inventoryService.getItem(itemId); if (!item || !item.price) { throw new UserError("Item not found or not for sale."); } const user = await userService.getOrCreateUser(interaction.user.id, interaction.user.username); if (!user) { throw new UserError("User profiles could not be loaded. Please try again later."); } // Double check balance here too, although service handles it, we want a nice message if ((user.balance ?? 0n) < item.price) { throw new UserError(`You need ${item.price} 🪙 to buy this item. You have ${user.balance?.toString() ?? "0"} 🪙.`); } await inventoryService.buyItem(user.id.toString(), item.id, 1n); await interaction.editReply({ content: `✅ **Success!** You bought **${item.name}** for ${item.price} 🪙.` }); }