import { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js';
import { db } from '../../core/db.js';
import { createInvoice } from '../payment/provider.js';
import { loadGuildPaymentConfig } from '../payment/config.js';
import { renderCategoryView } from './render.js';

export async function handleStoreInteraction(interaction, client) {
  const id = interaction.customId;

  // Category picker on main panel
  if (id.startsWith('store_category:') && interaction.isStringSelectMenu()) {
    const categoryId = parseInt(interaction.values[0]);
    return renderCategoryView(interaction, categoryId);
  }

  // Product picker (from category view)
  if (id === 'store_buy' && interaction.isStringSelectMenu()) {
    const productId = parseInt(interaction.values[0]);
    return startCheckout(interaction, productId);
  }
}

async function startCheckout(interaction, productId) {
  const product = db.prepare('SELECT * FROM products WHERE id = ? AND enabled = 1').get(productId);
  if (!product) return interaction.reply({ content: '❌ Produk tidak tersedia', ephemeral: true });

  const stockCount = db.prepare('SELECT COUNT(*) AS n FROM stock WHERE product_id = ? AND sold = 0').get(productId).n;
  if (product.auto_delivery && stockCount === 0) {
    return interaction.reply({ content: '❌ Stok habis. Coba lagi nanti.', ephemeral: true });
  }

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

  const invoiceId = `INV-${Date.now()}-${interaction.user.id.slice(-4)}`;
  const total = product.price;

  let payment;
  try {
    const payCfg = loadGuildPaymentConfig(interaction.guildId);
    let provider = 'mock';
    if (payCfg?.tripayEnabled) provider = 'tripay';
    else if (payCfg?.pakasirEnabled) provider = 'pakasir';
    payment = await createInvoice({
      invoiceId,
      amount: total,
      productName: product.name,
      buyerEmail: `${interaction.user.id}@discord.haikz`,
      buyerName: interaction.user.username,
      config: { provider, ...payCfg },
    });
  } catch (e) {
    return interaction.editReply({ content: `❌ Payment gateway error: ${e.message}` });
  }

  const result = db.prepare(`
    INSERT INTO orders (invoice_id, guild_id, user_id, product_id, qty, total, status, payment_provider, payment_url)
    VALUES (?, ?, ?, ?, 1, ?, 'pending', ?, ?)
  `).run(invoiceId, interaction.guildId, interaction.user.id, productId, total, payment.provider, payment.url);

  const embed = new EmbedBuilder()
    .setTitle('🧾 Invoice')
    .setColor(0xfbbf24)
    .addFields(
      { name: 'Invoice ID', value: `\`${invoiceId}\``, inline: true },
      { name: 'Produk', value: product.name, inline: true },
      { name: 'Total', value: `Rp${total.toLocaleString('id-ID')}`, inline: true },
      { name: 'Status', value: '⏳ Menunggu pembayaran', inline: false },
    )
    .setDescription(`Klik tombol **Bayar** di bawah untuk lanjut ke halaman pembayaran.\n\nSetelah bayar, order auto-process dalam <30 detik.`);

  const row = new ActionRowBuilder().addComponents(
    new ButtonBuilder().setLabel('💳 Bayar').setStyle(ButtonStyle.Link).setURL(payment.url),
  );

  await interaction.editReply({ embeds: [embed], components: [row] });
}
