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

export default {
  data: new SlashCommandBuilder()
    .setName('product')
    .setDescription('Kelola produk store')
    .setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
    .addSubcommand(s => s
      .setName('add')
      .setDescription('Tambah produk baru')
      .addStringOption(o => o.setName('name').setDescription('Nama produk').setRequired(true))
      .addIntegerOption(o => o.setName('price').setDescription('Harga (IDR)').setRequired(true).setMinValue(1000))
      .addStringOption(o => o.setName('description').setDescription('Deskripsi'))
      .addStringOption(o => o.setName('category').setDescription('Kategori (auto-create kalau belum ada)'))
      .addStringOption(o => o.setName('image_url').setDescription('URL gambar produk'))
      .addBooleanOption(o => o.setName('auto_delivery').setDescription('Auto delivery dari stok? (default: ya)')))
    .addSubcommand(s => s
      .setName('list')
      .setDescription('Lihat semua produk'))
    .addSubcommand(s => s
      .setName('remove')
      .setDescription('Hapus produk')
      .addIntegerOption(o => o.setName('id').setDescription('Product ID').setRequired(true))),

  async execute(interaction) {
    const sub = interaction.options.getSubcommand();

    if (sub === 'add') {
      const name = interaction.options.getString('name');
      const price = interaction.options.getInteger('price');
      const description = interaction.options.getString('description') || '';
      const categoryName = interaction.options.getString('category');
      const imageUrl = interaction.options.getString('image_url') || null;
      const autoDelivery = interaction.options.getBoolean('auto_delivery') ?? true;

      // Validation
      if (name.length > 100) return interaction.reply({ content: '❌ Nama produk max 100 karakter', ephemeral: true });
      if (description.length > 1000) return interaction.reply({ content: '❌ Deskripsi max 1000 karakter', ephemeral: true });
      if (imageUrl && !imageUrl.match(/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i)) {
        return interaction.reply({ content: '❌ URL gambar harus format: jpg, png, gif, atau webp', ephemeral: true });
      }

      // Find or create category by name
      let categoryId = null;
      if (categoryName) {
        let cat = db.prepare('SELECT id FROM categories WHERE guild_id = ? AND name = ?').get(interaction.guildId, categoryName);
        if (!cat) {
          const r = db.prepare('INSERT INTO categories (guild_id, name) VALUES (?, ?)').run(interaction.guildId, categoryName);
          categoryId = r.lastInsertRowid;
        } else {
          categoryId = cat.id;
        }
      }

      const r = db.prepare(
        'INSERT INTO products (guild_id, name, description, price, category_id, image_url, auto_delivery) VALUES (?,?,?,?,?,?,?)'
      ).run(interaction.guildId, name, description, price, categoryId, imageUrl, autoDelivery ? 1 : 0);

      const embed = new EmbedBuilder()
        .setTitle('✅ Produk dibuat')
        .setColor(0x10b981)
        .addFields(
          { name: 'ID', value: `\`${r.lastInsertRowid}\``, inline: true },
          { name: 'Nama', value: name, inline: true },
          { name: 'Harga', value: `Rp${price.toLocaleString('id-ID')}`, inline: true },
          { name: 'Kategori', value: categoryName || '_tidak ada_', inline: true },
          { name: 'Auto delivery', value: autoDelivery ? 'Ya' : 'Tidak', inline: true },
        );
      if (imageUrl) embed.setImage(imageUrl);
      embed.setFooter({ text: `Tambah stok: /stock add product_id:${r.lastInsertRowid} content:...` });

      await interaction.reply({ embeds: [embed], ephemeral: true });
      return;
    }

    if (sub === 'list') {
      const products = db.prepare(
        'SELECT p.*, (SELECT COUNT(*) FROM stock WHERE product_id = p.id AND sold = 0) AS stock_count FROM products WHERE guild_id = ? ORDER BY category, id'
      ).all(interaction.guildId);

      if (!products.length) {
        return interaction.reply({ content: 'Belum ada produk. Pakai `/product add` dulu.', ephemeral: true });
      }

      const embed = new EmbedBuilder()
        .setTitle('🛒 Daftar Produk')
        .setColor(0x5865f2)
        .setDescription(products.map(p =>
          `\`#${p.id}\` **${p.name}** — Rp${p.price.toLocaleString('id-ID')} · stok: ${p.stock_count} · ${p.enabled ? '✅' : '❌'}`
        ).join('\n'));

      await interaction.reply({ embeds: [embed], ephemeral: true });
      return;
    }

    if (sub === 'remove') {
      const id = interaction.options.getInteger('id');
      const r = db.prepare('DELETE FROM products WHERE id = ? AND guild_id = ?').run(id, interaction.guildId);
      await interaction.reply({
        content: r.changes ? `✅ Produk \`#${id}\` dihapus` : `❌ Produk tidak ditemukan`,
        ephemeral: true,
      });
    }
  },
};
