/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * LOOPUMAN STRIPE SERVICE
 * 13th January 2026
 * ═══════════════════════════════════════════════════════════════════════════════
 * 
 * Handles all Stripe payment processing for VAE purchases.
 * 
 * FEE MODEL (20% to platform):
 * - User wants Ⓥ1000 ($10 task value)
 * - User pays $12 (task value + 20%)
 * - User gets Ⓥ1000 credited
 * - Platform earns $2 (20%)
 * 
 * PRESET AMOUNTS:
 * | VAE     | Task Value | User Pays | Platform Fee |
 * |---------|------------|-----------|--------------|
 * | Ⓥ500   | $5.00      | $6.00     | $1.00        |
 * | Ⓥ1,000 | $10.00     | $12.00    | $2.00        |
 * | Ⓥ2,500 | $25.00     | $30.00    | $5.00        |
 * | Ⓥ5,000 | $50.00     | $60.00    | $10.00       |
 * | Ⓥ10,000| $100.00    | $120.00   | $20.00       |
 * 
 * ═══════════════════════════════════════════════════════════════════════════════
 */

'use strict';

const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const { createClient } = require('@supabase/supabase-js');
const express = require('express');

const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

// Telegram bot reference (set via setTelegramBot)
let telegramBot = null;

// ═══════════════════════════════════════════════════════════════════════════════
// CONFIGURATION
// ═══════════════════════════════════════════════════════════════════════════════

const CONFIG = {
  // Fee percentage (20% added to purchase)
  FEE_PERCENT: 20,
  
  // VAE to USD conversion (Ⓥ100 = $1)
  VAE_PER_USD: 100,
  
  // Preset purchase amounts (VAE)
  PRESET_AMOUNTS: [500, 1000, 2500, 5000, 10000],
  
  // Minimum custom amount (VAE)
  MIN_AMOUNT_VAE: 100,
  MAX_AMOUNT_VAE: 100000,
  
  // URLs
  SUCCESS_URL: process.env.STRIPE_SUCCESS_URL || 'https://loopuman.com/payment/success',
  CANCEL_URL: process.env.STRIPE_CANCEL_URL || 'https://loopuman.com/payment/cancelled'
};

// ═══════════════════════════════════════════════════════════════════════════════
// PRICE CALCULATIONS
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Calculate prices for a VAE amount
 * User wants Ⓥ1000 → pays $12 (base $10 + 20% fee)
 */
function calculatePrices(amountVae) {
  const baseUsd = amountVae / CONFIG.VAE_PER_USD;        // Task value in USD
  const feeUsd = baseUsd * (CONFIG.FEE_PERCENT / 100);   // 20% fee
  const totalUsd = baseUsd + feeUsd;                      // What user pays
  
  return {
    amountVae: Math.round(amountVae),
    baseUsd: Math.round(baseUsd * 100) / 100,
    feeUsd: Math.round(feeUsd * 100) / 100,
    totalUsd: Math.round(totalUsd * 100) / 100,
    totalCents: Math.round(totalUsd * 100)
  };
}

/**
 * Get all preset amounts with prices
 */
function getPresetAmounts() {
  return CONFIG.PRESET_AMOUNTS.map(vae => ({
    vae,
    ...calculatePrices(vae),
    display: `Ⓥ${vae.toLocaleString()}`
  }));
}

// ═══════════════════════════════════════════════════════════════════════════════
// CHECKOUT SESSION
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Create Stripe checkout session for VAE purchase
 */
async function createCheckoutSession(userId, amountVae, userEmail = null, telegramUsername = null) {
  // Validate amount
  if (amountVae < CONFIG.MIN_AMOUNT_VAE) {
    return { success: false, error: `Minimum purchase is Ⓥ${CONFIG.MIN_AMOUNT_VAE}` };
  }
  if (amountVae > CONFIG.MAX_AMOUNT_VAE) {
    return { success: false, error: `Maximum purchase is Ⓥ${CONFIG.MAX_AMOUNT_VAE.toLocaleString()}` };
  }
  
  // Calculate prices
  const prices = calculatePrices(amountVae);
  
  try {
    // Create Stripe session
    const sessionParams = {
      payment_method_types: ['card'],
      mode: 'payment',
      line_items: [{
        price_data: {
          currency: 'usd',
          product_data: {
            name: `Ⓥ${prices.amountVae.toLocaleString()} VAE Credits`,
            description: `Task budget: $${prices.baseUsd.toFixed(2)} + Platform fee: $${prices.feeUsd.toFixed(2)}`,
            images: ['https://loopuman.com/logo.png']
          },
          unit_amount: prices.totalCents
        },
        quantity: 1
      }],
      metadata: {
        user_id: userId,
        amount_vae: prices.amountVae.toString(),
        base_usd: prices.baseUsd.toString(),
        fee_usd: prices.feeUsd.toString(),
        total_usd: prices.totalUsd.toString(),
        telegram_username: telegramUsername || ''
      },
      success_url: `${CONFIG.SUCCESS_URL}?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: CONFIG.CANCEL_URL,
      expires_at: Math.floor(Date.now() / 1000) + 1800, // 30 minutes
      locale: 'en',  // Force USD display
    };
    
    // Add customer email if provided
    if (userEmail) {
      sessionParams.customer_email = userEmail;
    }
    
    const session = await stripe.checkout.sessions.create(sessionParams);
    
    // Record pending transaction
    await supabase
      .from('stripe_transactions')
      .insert({
        user_id: userId,
        stripe_session_id: session.id,
        amount_usd: prices.totalUsd,
        fee_usd: prices.feeUsd,
        net_usd: prices.baseUsd,
        amount_vae: prices.amountVae,
        status: 'pending',
        platform: 'telegram'
      });
    
    console.log(`✅ Checkout session created: ${session.id} for Ⓥ${prices.amountVae}`);
    
    return {
      success: true,
      sessionId: session.id,
      checkoutUrl: session.url,
      prices
    };
    
  } catch (error) {
    console.error('Stripe checkout error:', error);
    return { success: false, error: error.message };
  }
}

// ═══════════════════════════════════════════════════════════════════════════════
// WEBHOOK HANDLING
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Handle Stripe webhook events
 */
async function handleWebhook(payload, signature) {
  const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
  
  let event;
  try {
    event = stripe.webhooks.constructEvent(payload, signature, webhookSecret);
  } catch (err) {
    console.error('Webhook signature verification failed:', err.message);
    return { success: false, error: 'Invalid signature' };
  }
  
  console.log(`📨 Webhook received: ${event.type}`);
  
  switch (event.type) {
    case 'checkout.session.completed':
      await handleCheckoutCompleted(event.data.object);
      break;
      
    case 'checkout.session.expired':
      await handleCheckoutExpired(event.data.object);
      break;
      
    case 'payment_intent.payment_failed':
      await handlePaymentFailed(event.data.object);
      break;
      
    default:
      console.log(`Unhandled event type: ${event.type}`);
  }
  
  return { success: true };
}

/**
 * Handle successful checkout
 */
async function handleCheckoutCompleted(session) {
  console.log('=== PAYMENT COMPLETED ===');
  console.log(`Session: ${session.id}`);
  console.log(`Amount: $${session.amount_total / 100}`);
  
  const metadata = session.metadata || {};
  const userId = metadata.user_id;
  const amountVae = parseInt(metadata.amount_vae) || 0;
  const feeUsd = parseFloat(metadata.fee_usd) || 0;
  const totalUsd = parseFloat(metadata.total_usd) || 0;
  
  if (!userId || !amountVae) {
    console.error('Missing metadata in session:', session.id);
    return;
  }
  
  try {
    // Update transaction status
    await supabase
      .from('stripe_transactions')
      .update({
        status: 'completed',
        stripe_payment_intent: session.payment_intent,
        completed_at: new Date().toISOString()
      })
      .eq('stripe_session_id', session.id);
    
    // Credit user's deposit balance
    await supabase.rpc('credit_balance_safe', {
      p_user_id: userId,
      p_amount: amountVae,
      p_reference_id: session.id
    });
    
    // Record transaction
    await supabase
      .from('transactions')
      .insert({
        user_id: userId,
        type: 'deposit',
        amount: amountVae,
        balance_type: 'deposit',
        description: `Purchased Ⓥ${amountVae.toLocaleString()} for $${totalUsd.toFixed(2)}`,
        reference_type: 'stripe_session',
        reference_id: session.id,
        status: 'completed'
      });
    
    // Update user's total spent
    const { data: currentUser } = await supabase.from('app_users').select('total_spent').eq('id', userId).single();
    await supabase.from('app_users').update({
      total_spent: (currentUser?.total_spent || 0) + amountVae,
    }).eq('id', userId).catch(() => {
      console.log(`[Stripe] Could not update total_spent for ${userId}`);
    });
    
    console.log(`✅ Credited Ⓥ${amountVae} to user ${userId}`);
    
    // Send Telegram notification
    await notifyUser(userId, amountVae, totalUsd);
    
  } catch (error) {
    console.error('Error processing payment:', error);
  }
}

/**
 * Handle expired checkout session
 */
async function handleCheckoutExpired(session) {
  console.log(`Session expired: ${session.id}`);
  
  await supabase
    .from('stripe_transactions')
    .update({ status: 'expired' })
    .eq('stripe_session_id', session.id);
}

/**
 * Handle failed payment
 */
async function handlePaymentFailed(paymentIntent) {
  console.log(`Payment failed: ${paymentIntent.id}`);
  console.log(`Error: ${paymentIntent.last_payment_error?.message}`);
  
  await supabase
    .from('stripe_transactions')
    .update({
      status: 'failed',
      error_message: paymentIntent.last_payment_error?.message || 'Payment failed'
    })
    .eq('stripe_payment_intent', paymentIntent.id);
}

// ═══════════════════════════════════════════════════════════════════════════════
// USER NOTIFICATION
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Notify user of successful payment via Telegram
 */
async function notifyUser(userId, amountVae, amountUsd) {
  if (!telegramBot) {
    console.log('No Telegram bot configured for notifications');
    return;
  }
  
  try {
    // Get user's Telegram ID
    const { data: user } = await supabase
      .from('app_users')
      .select('telegram_id')
      .eq('id', userId)
      .single();
    
    if (!user?.telegram_id) return;
    
    // Get updated balance
    const { data: balance } = await supabase
      .from('vae_balances')
      .select('deposit_balance')
      .eq('user_id', userId)
      .single();
    
    const message = 
      `✅ *Payment Successful!*\n\n` +
      `💰 *Credited:* Ⓥ${amountVae.toLocaleString()}\n` +
      `💵 *Paid:* $${amountUsd.toFixed(2)}\n\n` +
      `📊 *New Balance:* Ⓥ${(balance?.deposit_balance || amountVae).toLocaleString()}\n\n` +
      `You can now post tasks with your VAE credits!`;
    
    await telegramBot.telegram.sendMessage(user.telegram_id, message, {
      parse_mode: 'Markdown',
      reply_markup: {
        inline_keyboard: [
          [{ text: '📋 Post a Task', callback_data: 'post_task' }],
          [{ text: '💰 View Balance', callback_data: 'view_balance' }]
        ]
      }
    });
    
  } catch (error) {
    console.error('Error sending notification:', error);
  }
}

/**
 * Set Telegram bot reference for notifications
 */
function setTelegramBot(bot) {
  telegramBot = bot;
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXPRESS WEBHOOK ROUTER
// ═══════════════════════════════════════════════════════════════════════════════

const webhookRouter = express.Router();

// IMPORTANT: This must use express.raw(), not express.json()
webhookRouter.post('/stripe', express.raw({ type: 'application/json' }), async (req, res) => {
  const signature = req.headers['stripe-signature'];
  
  try {
    const result = await handleWebhook(req.body, signature);
    
    if (result.success) {
      res.json({ received: true });
    } else {
      res.status(400).json({ error: result.error });
    }
  } catch (error) {
    console.error('Webhook error:', error);
    res.status(500).json({ error: 'Webhook processing failed' });
  }
});

// ═══════════════════════════════════════════════════════════════════════════════
// PURCHASE HISTORY
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Get user's purchase history
 */
async function getPurchaseHistory(userId, limit = 10) {
  const { data } = await supabase
    .from('stripe_transactions')
    .select('*')
    .eq('user_id', userId)
    .eq('status', 'completed')
    .order('completed_at', { ascending: false })
    .limit(limit);
  
  return data || [];
}

/**
 * Get purchase history display text
 */
async function getPurchaseHistoryText(userId) {
  const history = await getPurchaseHistory(userId, 5);
  
  if (history.length === 0) {
    return '📭 No purchase history yet.\n\nUse /buy to get VAE credits!';
  }
  
  let text = '📜 *Recent Purchases*\n\n';
  
  history.forEach((tx, i) => {
    const date = new Date(tx.completed_at).toLocaleDateString();
    text += `${i + 1}. Ⓥ${tx.amount_vae.toLocaleString()} for $${tx.amount_usd.toFixed(2)}\n`;
    text += `   📅 ${date}\n\n`;
  });
  
  return text;
}

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

module.exports = {
  // Core functions
  createCheckoutSession,
  handleWebhook,
  
  // Price calculations
  calculatePrices,
  getPresetAmounts,
  
  // History
  getPurchaseHistory,
  getPurchaseHistoryText,
  
  // Notification
  setTelegramBot,
  notifyUser,
  
  // Express router
  webhookRouter,
  
  // Config
  CONFIG
};
