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

export default {
  data: new SlashCommandBuilder()
    .setName('stock')
    .setDescription('Kelola stok produk')
    .setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
    .addSubcommand(s => s
      .setName('add')
      .setDescription('Tambah stok (1 baris = 1 item)')
      .addIntegerOption(o => o.setName('product_id').setDescription('Product ID').setRequired(true))
      .addStringOption(o => o.setName('content').setDescription('Isi stok (gunakan | untuk multi-item)').setRequired(true)))
    .addSubcommand(s => s
      .setName('view')
      .setDescription('Lihat stok produk')
      .addIntegerOption(o => o.setName('product_id').setDescription('Product ID').setRequired(true))),
  async execute(interaction) {
    const sub = interaction.options.getSubcommand();

    if (sub === 'add') {
      const productId = interaction.options.getInteger('product_id');
      const content = interaction.options.getString('content');
      const product = db.prepare('SELECT * FROM products WHERE id = ? AND guild_id = ?').get(productId, interaction.guildId);
      if (!product) return interaction.reply({ content: '❌ Produk tidak ada', ephemeral: true });

      // Validation
      if (content.length > 50000) return interaction.reply({ content: '❌ Content terlalu besar (max 50KB)', ephemeral: true });

      const items = content.split('|').map(s => s.trim()).filter(Boolean);
      if (items.length === 0) return interaction.reply({ content: '❌ Tidak ada item valid', ephemeral: true });
      if (items.length > 1000) return interaction.reply({ content: '❌ Max 1000 item per batch', ephemeral: true });

      const stmt = db.prepare('INSERT INTO stock (product_id, content) VALUES (?, ?)');
      const tx = db.transaction((items) => items.forEach(i => stmt.run(productId, i)));
      tx(items);

      await interaction.reply({
        content: `✅ ${items.length} item ditambah ke **${product.name}** (\`#${productId}\`)`,
        ephemeral: true,
      });
      return;
    }

    if (sub === 'view') {
      const productId = interaction.options.getInteger('product_id');
      const stats = db.prepare(`
        SELECT
          (SELECT COUNT(*) FROM stock WHERE product_id = ? AND sold = 0) AS available,
          (SELECT COUNT(*) FROM stock WHERE product_id = ? AND sold = 1) AS sold
      `).get(productId, productId);
      const product = db.prepare('SELECT * FROM products WHERE id = ?').get(productId);
      if (!product) return interaction.reply({ content: '❌ Produk tidak ada', ephemeral: true });

      const embed = new EmbedBuilder()
        .setTitle(`📦 Stok: ${product.name}`)
        .setColor(stats.available > 0 ? 0x10b981 : 0xef4444)
        .addFields(
          { name: 'Available', value: `${stats.available}`, inline: true },
          { name: 'Sold', value: `${stats.sold}`, inline: true },
        );
      await interaction.reply({ embeds: [embed], ephemeral: true });
    }
  },
};
