import { createCommand } from "@shared/lib/utils";
import { SlashCommandBuilder } from "discord.js";
import { inventoryService } from "@shared/modules/inventory/inventory.service";
import { userService } from "@shared/modules/user/user.service";
import { createWarningEmbed } from "@lib/embeds";
import { getInventoryEmbed } from "@/modules/inventory/inventory.view";

export const inventory = createCommand({
    data: new SlashCommandBuilder()
        .setName("inventory")
        .setDescription("View your or another user's inventory")
        .addUserOption(option =>
            option.setName("user")
                .setDescription("User to view")
                .setRequired(false)
        ),
    execute: async (interaction) => {
        await interaction.deferReply();

        const targetUser = interaction.options.getUser("user") || interaction.user;

        if (targetUser.bot) {
            await interaction.editReply({ embeds: [createWarningEmbed("Bots do not have inventories.", "Inventory Check")] });
            return;
        }

        const user = await userService.getOrCreateUser(targetUser.id, targetUser.username);
        if (!user) {
            await interaction.editReply({ embeds: [createWarningEmbed("Failed to load user data.", "Error")] });
            return;
        }

        const items = await inventoryService.getInventory(user.id.toString());

        if (!items || items.length === 0) {
            await interaction.editReply({ embeds: [createWarningEmbed("Inventory is empty.", `${user.username}'s Inventory`)] });
            return;
        }

        const embed = getInventoryEmbed(items, user.username);

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