/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * LOOPUMAN STRIPE BOT HANDLERS
 * 13th January 2026
 * ═══════════════════════════════════════════════════════════════════════════════
 * 
 * Telegram bot handlers for VAE purchase flow.
 * 
 * Commands:
 * - /buy - Start VAE purchase flow
 * - /topup - Alias for /buy
 * - /balance - Check current balance
 * - /history - View purchase history
 * 
 * ═══════════════════════════════════════════════════════════════════════════════
 */

'use strict';

const stripeService = require('./02-stripe-service');

/**
 * Register all Stripe-related bot handlers
 */
function register(bot, supabase) {
  
  // ═══════════════════════════════════════════════════════════════════════════════
  // BUY COMMAND
  // ═══════════════════════════════════════════════════════════════════════════════
  
  bot.command(['buy', 'topup'], async (ctx) => {
    const presets = stripeService.getPresetAmounts();
    
    let text = `💳 *Buy VAE Credits*\n\n`;
    text += `VAE is the currency for posting tasks on Loopuman.\n`;
    text += `Ⓥ100 = $1 USD\n\n`;
    text += `*Select an amount:*\n\n`;
    
    presets.forEach(p => {
      text += `• ${p.display} → Pay $${p.totalUsd.toFixed(2)}\n`;
    });
    
    text += `\n_20% platform fee included in price_`;
    
    // Create keyboard with preset amounts
    const keyboard = [];
    
    // Row 1: First 3 presets
    keyboard.push(presets.slice(0, 3).map(p => ({
      text: `${p.display} ($${p.totalUsd})`,
      callback_data: `buy_vae_${p.vae}`
    })));
    
    // Row 2: Next 2 presets
    keyboard.push(presets.slice(3, 5).map(p => ({
      text: `${p.display} ($${p.totalUsd})`,
      callback_data: `buy_vae_${p.vae}`
    })));
    
    // Row 3: Custom amount
    keyboard.push([
      { text: '✏️ Custom Amount', callback_data: 'buy_vae_custom' }
    ]);
    
    // Row 4: Cancel
    keyboard.push([
      { text: '❌ Cancel', callback_data: 'buy_cancel' }
    ]);
    
    await ctx.reply(text, {
      parse_mode: 'Markdown',
      reply_markup: { inline_keyboard: keyboard }
    });
  });
  
  // ═══════════════════════════════════════════════════════════════════════════════
  // PRESET AMOUNT SELECTION
  // ═══════════════════════════════════════════════════════════════════════════════
  
  bot.action(/^buy_vae_(\d+)$/, async (ctx) => {
    await ctx.answerCbQuery();
    
    const amountVae = parseInt(ctx.match[1]);
    const prices = stripeService.calculatePrices(amountVae);
    
    // Get user ID from database
    const userId = await getUserId(supabase, ctx.from.id);
    if (!userId) {
      return ctx.editMessageText(
        '❌ Please use /start first to create your account.',
        { parse_mode: 'Markdown' }
      );
    }
    
    // Show confirmation
    let text = `💳 *Confirm Purchase*\n\n`;
    text += `📦 *Amount:* Ⓥ${prices.amountVae.toLocaleString()}\n`;
    text += `💵 *Task Value:* $${prices.baseUsd.toFixed(2)}\n`;
    text += `🏷️ *Platform Fee:* $${prices.feeUsd.toFixed(2)} (20%)\n`;
    text += `━━━━━━━━━━━━━━━━━━\n`;
    text += `💰 *You Pay:* $${prices.totalUsd.toFixed(2)}\n\n`;
    text += `_Click "Pay Now" to proceed to secure checkout_`;
    
    await ctx.editMessageText(text, {
      parse_mode: 'Markdown',
      reply_markup: {
        inline_keyboard: [
          [{ text: `💳 Pay $${prices.totalUsd.toFixed(2)}`, callback_data: `confirm_buy_${amountVae}` }],
          [{ text: '« Back', callback_data: 'buy_back' }]
        ]
      }
    });
  });
  
  // ═══════════════════════════════════════════════════════════════════════════════
  // CONFIRM AND CREATE CHECKOUT
  // ═══════════════════════════════════════════════════════════════════════════════
  
  bot.action(/^confirm_buy_(\d+)$/, async (ctx) => {
    await ctx.answerCbQuery('Creating payment link...');
    
    const amountVae = parseInt(ctx.match[1]);
    
    // Get user ID
    const userId = await getUserId(supabase, ctx.from.id);
    if (!userId) {
      return ctx.editMessageText('❌ Account not found. Please /start first.');
    }
    
    // Create checkout session
    const result = await stripeService.createCheckoutSession(
      userId,
      amountVae,
      null, // email
      ctx.from.username
    );
    
    if (!result.success) {
      return ctx.editMessageText(`❌ Error: ${result.error}`);
    }
    
    // Show payment link
    let text = `✅ *Payment Link Ready*\n\n`;
    text += `📦 *Amount:* Ⓥ${result.prices.amountVae.toLocaleString()}\n`;
    text += `💰 *Price:* $${result.prices.totalUsd.toFixed(2)}\n\n`;
    text += `👇 Click the button below to pay securely via Stripe\n\n`;
    text += `⏰ _Link expires in 30 minutes_`;
    
    await ctx.editMessageText(text, {
      parse_mode: 'Markdown',
      reply_markup: {
        inline_keyboard: [
          [{ text: '💳 Pay Now (Secure)', url: result.checkoutUrl }],
          [{ text: '❌ Cancel', callback_data: 'buy_cancel' }]
        ]
      }
    });
  });
  
  // ═══════════════════════════════════════════════════════════════════════════════
  // CUSTOM AMOUNT
  // ═══════════════════════════════════════════════════════════════════════════════
  
  bot.action('buy_vae_custom', async (ctx) => {
    await ctx.answerCbQuery();
    
    ctx.session = ctx.session || {};
    ctx.session.awaitingCustomAmount = true;
    
    await ctx.editMessageText(
      `✏️ *Custom Amount*\n\n` +
      `Enter the amount of VAE you want to buy.\n\n` +
      `• Minimum: Ⓥ100 ($1.20)\n` +
      `• Maximum: Ⓥ100,000 ($1,200)\n\n` +
      `_Just type a number (e.g., 1500)_`,
      { 
        parse_mode: 'Markdown',
        reply_markup: {
          inline_keyboard: [
            [{ text: '« Back', callback_data: 'buy_back' }]
          ]
        }
      }
    );
  });
  
  // Handle custom amount text input
  bot.on('text', async (ctx, next) => {
    if (!ctx.session?.awaitingCustomAmount) {
      return next();
    }
    
    const input = ctx.message.text.replace(/[^0-9]/g, '');
    const amountVae = parseInt(input);
    
    if (isNaN(amountVae) || amountVae < 100) {
      return ctx.reply('❌ Please enter a valid number (minimum Ⓥ100)');
    }
    
    if (amountVae > 100000) {
      return ctx.reply('❌ Maximum amount is Ⓥ100,000. Contact support for larger purchases.');
    }
    
    ctx.session.awaitingCustomAmount = false;
    
    const prices = stripeService.calculatePrices(amountVae);
    
    let text = `💳 *Confirm Custom Purchase*\n\n`;
    text += `📦 *Amount:* Ⓥ${prices.amountVae.toLocaleString()}\n`;
    text += `💵 *Task Value:* $${prices.baseUsd.toFixed(2)}\n`;
    text += `🏷️ *Platform Fee:* $${prices.feeUsd.toFixed(2)} (20%)\n`;
    text += `━━━━━━━━━━━━━━━━━━\n`;
    text += `💰 *You Pay:* $${prices.totalUsd.toFixed(2)}`;
    
    await ctx.reply(text, {
      parse_mode: 'Markdown',
      reply_markup: {
        inline_keyboard: [
          [{ text: `💳 Pay $${prices.totalUsd.toFixed(2)}`, callback_data: `confirm_buy_${amountVae}` }],
          [{ text: '« Change Amount', callback_data: 'buy_vae_custom' }],
          [{ text: '❌ Cancel', callback_data: 'buy_cancel' }]
        ]
      }
    });
  });
  
  // ═══════════════════════════════════════════════════════════════════════════════
  // NAVIGATION
  // ═══════════════════════════════════════════════════════════════════════════════
  
  bot.action('buy_back', async (ctx) => {
    await ctx.answerCbQuery();
    ctx.session = ctx.session || {};
    ctx.session.awaitingCustomAmount = false;
    
    // Re-trigger buy command
    const presets = stripeService.getPresetAmounts();
    
    let text = `💳 *Buy VAE Credits*\n\n`;
    text += `VAE is the currency for posting tasks on Loopuman.\n`;
    text += `Ⓥ100 = $1 USD\n\n`;
    text += `*Select an amount:*`;
    
    const keyboard = [];
    keyboard.push(presets.slice(0, 3).map(p => ({
      text: `${p.display} ($${p.totalUsd})`,
      callback_data: `buy_vae_${p.vae}`
    })));
    keyboard.push(presets.slice(3, 5).map(p => ({
      text: `${p.display} ($${p.totalUsd})`,
      callback_data: `buy_vae_${p.vae}`
    })));
    keyboard.push([
      { text: '✏️ Custom Amount', callback_data: 'buy_vae_custom' }
    ]);
    keyboard.push([
      { text: '❌ Cancel', callback_data: 'buy_cancel' }
    ]);
    
    await ctx.editMessageText(text, {
      parse_mode: 'Markdown',
      reply_markup: { inline_keyboard: keyboard }
    });
  });
  
  bot.action('buy_cancel', async (ctx) => {
    await ctx.answerCbQuery('Cancelled');
    ctx.session = ctx.session || {};
    ctx.session.awaitingCustomAmount = false;
    
    await ctx.editMessageText(
      '❌ Purchase cancelled.\n\nUse /buy anytime to get VAE credits!'
    );
  });
  
  // ═══════════════════════════════════════════════════════════════════════════════
  // BALANCE COMMAND
  // ═══════════════════════════════════════════════════════════════════════════════
  
  bot.command('balance', async (ctx) => {
    const userId = await getUserId(supabase, ctx.from.id);
    if (!userId) {
      return ctx.reply('❌ Please /start first to create your account.');
    }
    
    const { data: balance } = await supabase
      .from('vae_balances')
      .select('*')
      .eq('user_id', userId)
      .single();
    
    const deposit = balance?.deposit_balance || 0;
    const earnings = balance?.earnings_balance || 0;
    const referral = balance?.referral_earnings || 0;
    const total = deposit + earnings + referral;
    
    let text = `💰 *Your Balance*\n\n`;
    text += `📊 *Total:* Ⓥ${total.toLocaleString()} ($${(total/100).toFixed(2)})\n\n`;
    text += `*Breakdown:*\n`;
    text += `├ 💵 Deposits: Ⓥ${deposit.toLocaleString()}\n`;
    text += `├ ✅ Earnings: Ⓥ${earnings.toLocaleString()}\n`;
    text += `└ 🔗 Referrals: Ⓥ${referral.toLocaleString()}\n\n`;
    text += `_Deposits = for posting tasks_\n`;
    text += `_Earnings = from completed tasks (withdrawable)_`;
    
    await ctx.reply(text, {
      parse_mode: 'Markdown',
      reply_markup: {
        inline_keyboard: [
          [{ text: '💳 Buy More VAE', callback_data: 'buy_back' }],
          [{ text: '💸 Withdraw', callback_data: 'withdraw' }]
        ]
      }
    });
  });
  
  // ═══════════════════════════════════════════════════════════════════════════════
  // PURCHASE HISTORY
  // ═══════════════════════════════════════════════════════════════════════════════
  
  bot.command('history', async (ctx) => {
    const userId = await getUserId(supabase, ctx.from.id);
    if (!userId) {
      return ctx.reply('❌ Please /start first.');
    }
    
    const text = await stripeService.getPurchaseHistoryText(userId);
    
    await ctx.reply(text, {
      parse_mode: 'Markdown',
      reply_markup: {
        inline_keyboard: [
          [{ text: '💳 Buy VAE', callback_data: 'buy_back' }]
        ]
      }
    });
  });
  
  console.log('✅ Stripe bot handlers registered');
}

// ═══════════════════════════════════════════════════════════════════════════════
// HELPER
// ═══════════════════════════════════════════════════════════════════════════════

async function getUserId(supabase, telegramId) {
  const { data } = await supabase
    .from('app_users')
    .select('id')
    .eq('telegram_id', telegramId.toString())
    .single();
  return data?.id;
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXPORTS
// ═══════════════════════════════════════════════════════════════════════════════

module.exports = { register };
