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

export default {
  data: new SlashCommandBuilder()
    .setName('send')
    .setDescription('Manual delivery - kirim produk ke user')
    .setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
    .addUserOption(o => o.setName('user').setDescription('User tujuan').setRequired(true))
    .addStringOption(o => o.setName('sku').setDescription('SKU/Code produk (contoh: d3_8a4f)').setRequired(true))
    .addIntegerOption(o => o.setName('quantity').setDescription('Jumlah (default: 1)').setMinValue(1).setMaxValue(10)),

  async execute(interaction) {
    // Only owner or admin
    if (!isOwner(interaction.user.id) && !interaction.member.permissions.has(PermissionFlagsBits.Administrator)) {
      return interaction.reply({ content: '❌ Owner/Admin only', ephemeral: true });
    }

    const targetUser = interaction.options.getUser('user');
    const sku = interaction.options.getString('sku');
    const quantity = interaction.options.getInteger('quantity') || 1;

    await interaction.deferReply({ ephemeral: true });

    try {
      // Get product by SKU
      const product = db.prepare('SELECT * FROM products WHERE sku = ? AND guild_id = ?').get(sku, interaction.guildId);
      if (!product) {
        return interaction.editReply({ content: `❌ Produk dengan SKU \`${sku}\` tidak ditemukan` });
      }

      // Get available stock
      const stocks = db.prepare('SELECT * FROM stock WHERE product_id = ? AND sold = 0 LIMIT ?').all(productId, quantity);
      if (stocks.length < quantity) {
        return interaction.editReply({
          content: `❌ Stock tidak cukup. Tersedia: ${stocks.length}, diminta: ${quantity}`,
        });
      }

      // Mark stock as sold
      const tx = db.transaction(() => {
        for (const stock of stocks) {
          db.prepare('UPDATE stock SET sold = 1, sold_to = ?, sold_at = unixepoch() WHERE id = ?')
            .run(targetUser.id, stock.id);
        }
      });
      tx();

      // Prepare delivery content
      const deliveryContent = stocks.map(s => s.content).join('\n');

      // Send DM to user
      try {
        const embed = new EmbedBuilder()
          .setTitle('📦 Manual Delivery')
          .setColor(0x10b981)
          .addFields(
            { name: 'Produk', value: product.name, inline: true },
            { name: 'Quantity', value: `${quantity}`, inline: true },
            { name: 'Dari', value: `${interaction.user.tag}`, inline: true },
          )
          .setDescription('```\n' + deliveryContent + '\n```')
          .setFooter({ text: `Guild: ${interaction.guild.name}` })
          .setTimestamp();

        await targetUser.send({ embeds: [embed] });

        // Audit log
        audit(interaction.guildId, interaction.user.id, 'manual_delivery', {
          target_user: targetUser.id,
          product_id: product.id,
          product_name: product.name,
          product_sku: product.sku,
          quantity,
          stock_ids: stocks.map(s => s.id),
        });

        // Success reply
        await interaction.editReply({
          embeds: [new EmbedBuilder()
            .setTitle('✅ Manual Delivery Berhasil')
            .setColor(0x10b981)
            .addFields(
              { name: 'Ke', value: `${targetUser.tag} (\`${targetUser.id}\`)`, inline: false },
              { name: 'Produk', value: `${product.name}${product.sku ? ` (\`${product.sku}\`)` : ''}`, inline: true },
              { name: 'Quantity', value: `${quantity}`, inline: true },
            )
            .setDescription('DM telah dikirim ke user.')],
        });
      } catch (dmError) {
        // DM failed - rollback stock
        const rollback = db.transaction(() => {
          for (const stock of stocks) {
            db.prepare('UPDATE stock SET sold = 0, sold_to = NULL, sold_at = NULL WHERE id = ?').run(stock.id);
          }
        });
        rollback();

        return interaction.editReply({
          content: `❌ Gagal kirim DM ke ${targetUser.tag}. Stock tidak dikurangi.\n\nKemungkinan:\n- User block bot\n- DM closed\n- User left server`,
        });
      }
    } catch (e) {
      console.error('[/send]', e);
      await interaction.editReply({ content: `❌ Error: ${e.message}` });
    }
  },
};
