import { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits, ChannelType, ActionRowBuilder, StringSelectMenuBuilder } from 'discord.js';
import { db } from '../core/db.js';

export default {
  data: new SlashCommandBuilder()
    .setName('store')
    .setDescription('Kirim panel store ke channel')
    .setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
    .addSubcommand(s => s
      .setName('panel')
      .setDescription('Kirim panel produk')
      .addChannelOption(o => o.setName('channel').setDescription('Target channel').addChannelTypes(ChannelType.GuildText).setRequired(true))),
  async execute(interaction) {
    const ch = interaction.options.getChannel('channel');
    const products = db.prepare(`
      SELECT p.*, c.name AS category_name
      FROM products p
      LEFT JOIN categories c ON c.id = p.category_id
      WHERE p.guild_id = ? AND p.enabled = 1
      ORDER BY c.sort_order, p.sort_order, p.id
    `).all(interaction.guildId);
    if (!products.length) return interaction.reply({ content: '❌ Belum ada produk. `/product add` dulu.', ephemeral: true });

    const embed = new EmbedBuilder()
      .setTitle('🛒 Store')
      .setColor(0x5865f2)
      .setDescription('Pilih produk dari menu di bawah untuk membeli.');

    // Group by category for nicer display
    const grouped = {};
    for (const p of products) {
      const cat = p.category_name || 'Lainnya';
      grouped[cat] = grouped[cat] || [];
      grouped[cat].push(p);
    }
    for (const [cat, items] of Object.entries(grouped)) {
      embed.addFields({
        name: `📁 ${cat}`,
        value: items.map(p => `\`#${p.id}\` **${p.name}** — Rp${p.price.toLocaleString('id-ID')}`).join('\n'),
      });
    }

    const select = new StringSelectMenuBuilder()
      .setCustomId('store_buy')
      .setPlaceholder('Pilih produk untuk dibeli…')
      .addOptions(products.slice(0, 25).map(p => ({
        label: `${p.name} — Rp${p.price.toLocaleString('id-ID')}`.slice(0, 100),
        description: (p.description || p.category).slice(0, 100),
        value: `${p.id}`,
      })));

    await ch.send({ embeds: [embed], components: [new ActionRowBuilder().addComponents(select)] });
    await interaction.reply({ content: `✅ Panel store dikirim ke ${ch}`, ephemeral: true });
  },
};
