const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { getServerMode, getEmbedColor, EMBED_COLORS } = require('../utils/modeHelper');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('inventory')
    .setDescription('View your inventory')
    .addUserOption(option =>
      option.setName('user')
        .setDescription('User to view inventory of')
        .setRequired(false)
    ),

  async execute(interaction, supabase, client) {
    const targetUser = interaction.options.getUser('user') || interaction.user;
    const mode = await getServerMode(supabase, interaction.guildId);
    const guildId = interaction.guildId;

    if (!supabase) {
      return interaction.reply({ content: 'Inventory system unavailable.', ephemeral: true });
    }

    try {
      const { data: items } = await supabase
        .from('user_inventory')
        .select('*, shop_items(*)')
        .eq('guild_id', guildId)
        .eq('user_id', targetUser.id);

      if (!items || items.length === 0) {
        const embed = new EmbedBuilder()
          .setColor(getEmbedColor(mode))
          .setTitle(`🎒 ${targetUser.username}'s Inventory`)
          .setDescription('Inventory is empty. Buy items from the `/shop`!')
          .setThumbnail(targetUser.displayAvatarURL({ size: 128 }))
          .setTimestamp();
        return interaction.reply({ embeds: [embed] });
      }

      const itemList = items.map(inv => {
        const item = inv.shop_items;
        if (!item) return null;
        return `${item.emoji || '📦'} **${item.name}** x${inv.quantity}`;
      }).filter(Boolean).join('\n');

      const embed = new EmbedBuilder()
        .setColor(getEmbedColor(mode))
        .setTitle(`🎒 ${targetUser.username}'s Inventory`)
        .setDescription(itemList || 'No items')
        .setThumbnail(targetUser.displayAvatarURL({ size: 128 }))
        .setFooter({ text: `${items.length} unique item(s)` })
        .setTimestamp();

      await interaction.reply({ embeds: [embed] });
    } catch (e) {
      await interaction.reply({ content: 'Failed to fetch inventory.', ephemeral: true });
    }
  },
};
