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

// processOrderPaid: tandai order lunas + alokasi stok + kirim DM.
// Idempotent (V3): order yang bukan 'pending' diabaikan.
// V2 (amount tampering): kalau expectedAmount diberi, WAJIB == order.total, kalau tidak -> tolak.
export async function processOrderPaid(client, invoiceId, expectedAmount = null) {
  const order = db.prepare('SELECT * FROM orders WHERE invoice_id = ?').get(invoiceId);
  if (!order) return { ok: false, error: 'Order not found' };
  if (order.status !== 'pending') return { ok: false, error: `Order status is ${order.status}` };

  // V2: verifikasi jumlah bayar == total order (cegah "bayar Rp1 klaim lunas")
  if (expectedAmount != null) {
    const paid = Math.round(Number(expectedAmount));
    if (!Number.isFinite(paid) || paid !== Math.round(Number(order.total))) {
      console.warn(`[delivery] AMOUNT MISMATCH invoice=${invoiceId} expected=${order.total} got=${expectedAmount}`);
      return { ok: false, error: `amount mismatch (expected ${order.total}, got ${expectedAmount})` };
    }
  }

  // Allocate stock if auto_delivery
  const product = db.prepare('SELECT * FROM products WHERE id = ?').get(order.product_id);
  let deliveredContent = null;

  if (product.auto_delivery) {
    // Use transaction with optimistic locking to prevent race condition
    const allocateStock = db.transaction(() => {
      const result = db.prepare(`
        UPDATE stock SET sold = 1, sold_to = ?, sold_at = unixepoch()
        WHERE id = (SELECT id FROM stock WHERE product_id = ? AND sold = 0 LIMIT 1)
      `).run(order.user_id, order.product_id);

      if (result.changes === 0) return null; // No stock available

      // Get the allocated stock content
      return db.prepare('SELECT content FROM stock WHERE product_id = ? AND sold_to = ? ORDER BY sold_at DESC LIMIT 1')
        .get(order.product_id, order.user_id);
    });

    const stock = allocateStock();
    if (!stock) {
      // Mark as paid but pending delivery
      db.prepare('UPDATE orders SET status = ?, paid_at = unixepoch() WHERE id = ?').run('paid', order.id);
      return { ok: true, status: 'paid_pending_stock' };
    }
    deliveredContent = stock.content;
  }

  db.prepare(`
    UPDATE orders SET status = 'delivered', paid_at = unixepoch(), delivered_at = unixepoch(), delivered_content = ?
    WHERE id = ?
  `).run(deliveredContent, order.id);

  // DM the user
  try {
    const user = await client.users.fetch(order.user_id);
    const embed = new EmbedBuilder()
      .setTitle('✅ Pembayaran Diterima')
      .setColor(0x10b981)
      .addFields(
        { name: 'Invoice', value: `\`${order.invoice_id}\``, inline: true },
        { name: 'Produk', value: product.name, inline: true },
        { name: 'Total', value: `Rp${order.total.toLocaleString('id-ID')}`, inline: true },
      );
    if (deliveredContent) embed.addFields({ name: '📦 Item', value: '```\n' + deliveredContent + '\n```' });
    await user.send({ embeds: [embed] });
  } catch (e) {
    console.warn('[delivery] DM failed:', e.message);
  }

  return { ok: true, status: 'delivered' };
}
