import { ButtonInteraction, MessageFlags } from "discord.js";
import { inventoryService } from "@shared/modules/inventory/inventory.service";
import { userService } from "@shared/modules/user/user.service";
import { UserError } from "@shared/lib/errors";
import { SHOP_CUSTOM_IDS } from "./economy.types";

export async function handleShopInteraction(interaction: ButtonInteraction) {
    if (!interaction.customId.startsWith(SHOP_CUSTOM_IDS.BUY_PREFIX)) return;

    await interaction.deferReply({ flags: MessageFlags.Ephemeral });

    const itemId = parseInt(interaction.customId.replace(SHOP_CUSTOM_IDS.BUY_PREFIX, ""));
    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} 🪙.` });
}
