/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * LOOPUMAN REFERRAL SYSTEM
 * ═══════════════════════════════════════════════════════════════════════════════
 * 
 * Viral growth engine for Loopuman.
 * 
 * WORKER REFERRALS:
 * - Earn 1% of your referral's earnings FOREVER
 * - No cap on referrals
 * - Passive income stream
 * 
 * REQUESTER REFERRALS:
 * - Referrer gets 10% bonus VAE on referral's first purchase
 * - New user gets 5% bonus VAE on first purchase
 * 
 * TRACKING:
 * - Unique referral codes per user
 * - Deep links that work across Telegram/WhatsApp
 * - Real-time earnings tracking
 * 
 * ═══════════════════════════════════════════════════════════════════════════════
 */

'use strict';

const { createClient } = require('@supabase/supabase-js');
const crypto = require('crypto');

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

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

const CONFIG = {
  // Worker referral: % of referee's earnings paid to referrer
  WORKER_REFERRAL_PERCENT: 1,
  
  // Requester referral bonuses
  REQUESTER_REFERRER_BONUS_PERCENT: 10, // Referrer gets 10% of first purchase
  REQUESTER_REFEREE_BONUS_PERCENT: 5,   // New user gets 5% bonus
  
  // Limits
  MAX_REFERRAL_BONUS_VAE: 10000, // Max Ⓥ10,000 bonus per referral
  
  // Referral code format
  CODE_LENGTH: 8,
  
  // Deep link templates
  TELEGRAM_BOT_USERNAME: process.env.TELEGRAM_BOT_USERNAME || 'LoopumanBot',
  WHATSAPP_NUMBER: process.env.WHATSAPP_NUMBER || '447801499655'
};

// ═══════════════════════════════════════════════════════════════════════════════
// REFERRAL CODE GENERATION
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Generate unique referral code for a user
 * Format: LOOP-XXXX (8 alphanumeric chars)
 */
function generateReferralCode() {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // Removed confusing chars
  let code = '';
  for (let i = 0; i < CONFIG.CODE_LENGTH; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return code;
}

/**
 * Get or create referral code for user
 */
async function getUserReferralCode(userId) {
  // Check if user already has a code
  const { data: user } = await supabase
    .from('app_users')
    .select('referral_code')
    .eq('id', userId)
    .single();
  
  if (user?.referral_code) {
    return user.referral_code;
  }
  
  // Generate new unique code
  let code;
  let isUnique = false;
  let attempts = 0;
  
  while (!isUnique && attempts < 10) {
    code = generateReferralCode();
    const { data: existing } = await supabase
      .from('app_users')
      .select('id')
      .eq('referral_code', code)
      .single();
    
    if (!existing) {
      isUnique = true;
    }
    attempts++;
  }
  
  // Save code to user
  await supabase
    .from('app_users')
    .update({ referral_code: code })
    .eq('id', userId);
  
  return code;
}

// ═══════════════════════════════════════════════════════════════════════════════
// REFERRAL LINKS
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Generate all referral links for a user
 */
async function getReferralLinks(userId) {
  const code = await getUserReferralCode(userId);
  
  return {
    code,
    telegram: `https://t.me/${CONFIG.TELEGRAM_BOT_USERNAME}?start=ref_${code}`,
    whatsapp: `https://wa.me/${CONFIG.WHATSAPP_NUMBER}?text=ref_${code}`,
    universal: `https://loopuman.com/join?ref=${code}`,
    shareText: `🚀 Join Loopuman and earn money from your phone!\n\n` +
               `✅ Complete simple tasks\n` +
               `✅ Get paid instantly in crypto\n` +
               `✅ Build portable reputation\n\n` +
               `Use my referral code: ${code}\n` +
               `👉 https://t.me/${CONFIG.TELEGRAM_BOT_USERNAME}?start=ref_${code}`
  };
}

// ═══════════════════════════════════════════════════════════════════════════════
// PROCESS REFERRAL
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Process referral when new user signs up
 * Called during user registration
 */
async function processReferral(newUserId, referralCode) {
  if (!referralCode) return { success: false, error: 'No referral code' };
  
  // Clean the code
  const code = referralCode.replace('ref_', '').toUpperCase().trim();
  
  // Find referrer
  const { data: referrer } = await supabase
    .from('app_users')
    .select('id, telegram_id, telegram_username')
    .eq('referral_code', code)
    .single();
  
  if (!referrer) {
    return { success: false, error: 'Invalid referral code' };
  }
  
  // Prevent self-referral
  if (referrer.id === newUserId) {
    return { success: false, error: 'Cannot refer yourself' };
  }
  
  // Check if already referred
  const { data: existingRef } = await supabase
    .from('referrals')
    .select('id')
    .eq('referee_id', newUserId)
    .single();
  
  if (existingRef) {
    return { success: false, error: 'User already referred' };
  }
  
  // Record referral
  const { error } = await supabase
    .from('referrals')
    .insert({
      referrer_id: referrer.id,
      referee_id: newUserId,
      referral_code: code,
      status: 'active',
      created_at: new Date().toISOString()
    });
  
  if (error) {
    console.error('Referral record error:', error);
    return { success: false, error: 'Failed to record referral' };
  }
  
  // Update referrer's stats
  await supabase.rpc('increment_referral_count', { user_id: referrer.id });
  
  console.log(`✅ Referral recorded: ${referrer.telegram_username} → new user`);
  
  return {
    success: true,
    referrer: {
      id: referrer.id,
      username: referrer.telegram_username
    }
  };
}

// ═══════════════════════════════════════════════════════════════════════════════
// CALCULATE REFERRAL EARNINGS
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Calculate and credit referral bonus when worker earns
 * Called after each task completion payment
 */
async function processWorkerReferralBonus(workerId, earningsVae) {
  // Get referrer
  const { data: referral } = await supabase
    .from('referrals')
    .select('referrer_id, status')
    .eq('referee_id', workerId)
    .eq('status', 'active')
    .single();
  
  if (!referral) return null;
  
  // Calculate 1% bonus
  const bonusVae = Math.floor(earningsVae * (CONFIG.WORKER_REFERRAL_PERCENT / 100));
  
  if (bonusVae < 1) return null;
  
  // Credit referrer
  const { data: balance } = await supabase
    .from('vae_balances')
    .select('referral_earnings')
    .eq('user_id', referral.referrer_id)
    .single();
  
  const newBalance = (balance?.referral_earnings || 0) + bonusVae;
  
  await supabase
    .from('vae_balances')
    .upsert({
      user_id: referral.referrer_id,
      referral_earnings: newBalance,
      updated_at: new Date().toISOString()
    }, { onConflict: 'user_id' });
  
  // Record transaction
  await supabase
    .from('referral_earnings')
    .insert({
      referrer_id: referral.referrer_id,
      referee_id: workerId,
      source_amount: earningsVae,
      bonus_amount: bonusVae,
      bonus_percent: CONFIG.WORKER_REFERRAL_PERCENT
    });
  
  // Update total earned from this referral
  await supabase
    .from('referrals')
    .update({
      total_earnings: supabase.sql`total_earnings + ${bonusVae}`,
      updated_at: new Date().toISOString()
    })
    .eq('referee_id', workerId);
  
  return { referrerId: referral.referrer_id, bonusVae };
}

/**
 * Process requester referral bonus on first purchase
 */
async function processRequesterReferralBonus(requesterId, purchaseVae) {
  // Get referral
  const { data: referral } = await supabase
    .from('referrals')
    .select('referrer_id, first_purchase_processed')
    .eq('referee_id', requesterId)
    .single();
  
  if (!referral || referral.first_purchase_processed) return null;
  
  // Calculate bonuses
  const referrerBonus = Math.min(
    Math.floor(purchaseVae * (CONFIG.REQUESTER_REFERRER_BONUS_PERCENT / 100)),
    CONFIG.MAX_REFERRAL_BONUS_VAE
  );
  
  const refereeBonus = Math.min(
    Math.floor(purchaseVae * (CONFIG.REQUESTER_REFEREE_BONUS_PERCENT / 100)),
    CONFIG.MAX_REFERRAL_BONUS_VAE
  );
  
  // Credit referrer
  if (referrerBonus > 0) {
    await supabase.rpc('credit_deposit_balance', {
      p_user_id: referral.referrer_id,
      p_amount: referrerBonus
    });
  }
  
  // Credit referee (new user)
  if (refereeBonus > 0) {
    await supabase.rpc('credit_deposit_balance', {
      p_user_id: requesterId,
      p_amount: refereeBonus
    });
  }
  
  // Mark as processed
  await supabase
    .from('referrals')
    .update({
      first_purchase_processed: true,
      first_purchase_amount: purchaseVae,
      referrer_bonus: referrerBonus,
      referee_bonus: refereeBonus,
      updated_at: new Date().toISOString()
    })
    .eq('referee_id', requesterId);
  
  return { referrerBonus, refereeBonus };
}

// ═══════════════════════════════════════════════════════════════════════════════
// REFERRAL STATISTICS
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Get referral statistics for a user
 */
async function getReferralStats(userId) {
  // Get referrals made
  const { data: referrals } = await supabase
    .from('referrals')
    .select(`
      id,
      referee_id,
      status,
      total_earnings,
      created_at,
      referee:app_users!referee_id(telegram_username, tasks_completed)
    `)
    .eq('referrer_id', userId)
    .order('created_at', { ascending: false });
  
  // Get total referral earnings
  const { data: balance } = await supabase
    .from('vae_balances')
    .select('referral_earnings')
    .eq('user_id', userId)
    .single();
  
  // Calculate stats
  const totalReferrals = referrals?.length || 0;
  const activeReferrals = referrals?.filter(r => r.referee?.tasks_completed > 0).length || 0;
  const totalEarnings = balance?.referral_earnings || 0;
  
  // Get this month's earnings
  const monthStart = new Date();
  monthStart.setDate(1);
  monthStart.setHours(0, 0, 0, 0);
  
  const { data: monthlyEarnings } = await supabase
    .from('referral_earnings')
    .select('bonus_amount')
    .eq('referrer_id', userId)
    .gte('created_at', monthStart.toISOString());
  
  const thisMonthEarnings = monthlyEarnings?.reduce((sum, e) => sum + e.bonus_amount, 0) || 0;
  
  return {
    totalReferrals,
    activeReferrals,
    totalEarnings,
    thisMonthEarnings,
    referrals: referrals?.slice(0, 10) || [] // Last 10
  };
}

/**
 * Generate referral display text for Telegram
 */
async function getReferralDisplayText(userId) {
  const [links, stats] = await Promise.all([
    getReferralLinks(userId),
    getReferralStats(userId)
  ]);
  
  let text = `🔗 *YOUR REFERRAL PROGRAM*\n\n`;
  
  text += `📊 *Your Stats*\n`;
  text += `├ Total Referrals: ${stats.totalReferrals}\n`;
  text += `├ Active Workers: ${stats.activeReferrals}\n`;
  text += `├ This Month: Ⓥ${stats.thisMonthEarnings.toLocaleString()}\n`;
  text += `└ All Time: Ⓥ${stats.totalEarnings.toLocaleString()}\n\n`;
  
  text += `💰 *How It Works*\n`;
  text += `• Earn *1% of everything* your referrals earn\n`;
  text += `• No limits - passive income forever!\n`;
  text += `• Paid automatically to your wallet\n\n`;
  
  text += `🎁 *Your Referral Code*\n`;
  text += `\`${links.code}\`\n\n`;
  
  text += `📱 *Share Link*\n`;
  text += `${links.telegram}\n\n`;
  
  text += `_Tap the code to copy, share with friends!_`;
  
  return text;
}

// ═══════════════════════════════════════════════════════════════════════════════
// LEADERBOARD
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Get top referrers leaderboard
 */
async function getReferralLeaderboard(limit = 10) {
  const { data } = await supabase
    .from('app_users')
    .select(`
      telegram_username,
      referral_count,
      vae_balances(referral_earnings)
    `)
    .gt('referral_count', 0)
    .order('referral_count', { ascending: false })
    .limit(limit);
  
  return data?.map((user, index) => ({
    rank: index + 1,
    username: user.telegram_username || 'Anonymous',
    referrals: user.referral_count,
    earnings: user.vae_balances?.[0]?.referral_earnings || 0
  })) || [];
}

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

module.exports = {
  // Core functions
  generateReferralCode,
  getUserReferralCode,
  getReferralLinks,
  processReferral,
  
  // Bonus processing
  processWorkerReferralBonus,
  processRequesterReferralBonus,
  
  // Statistics
  getReferralStats,
  getReferralDisplayText,
  getReferralLeaderboard,
  
  // Config
  CONFIG
};
