/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * LOOPUMAN ADMIN ANALYTICS DASHBOARD
 * ═══════════════════════════════════════════════════════════════════════════════
 * 
 * Real-time analytics for solopreneur management.
 * 
 * METRICS TRACKED:
 * - Revenue & transactions
 * - User growth
 * - Task activity
 * - Worker performance
 * - Platform health
 * - AI automation stats
 * 
 * ACCESS: Via Admin Telegram Bot
 * 
 * ═══════════════════════════════════════════════════════════════════════════════
 */

'use strict';

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

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

// ═══════════════════════════════════════════════════════════════════════════════
// TIME HELPERS
// ═══════════════════════════════════════════════════════════════════════════════

function getTimeRanges() {
  const now = new Date();
  
  const todayStart = new Date(now);
  todayStart.setHours(0, 0, 0, 0);
  
  const yesterdayStart = new Date(todayStart);
  yesterdayStart.setDate(yesterdayStart.getDate() - 1);
  
  const weekStart = new Date(todayStart);
  weekStart.setDate(weekStart.getDate() - 7);
  
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  
  return {
    now: now.toISOString(),
    todayStart: todayStart.toISOString(),
    yesterdayStart: yesterdayStart.toISOString(),
    weekStart: weekStart.toISOString(),
    monthStart: monthStart.toISOString()
  };
}

// ═══════════════════════════════════════════════════════════════════════════════
// REVENUE ANALYTICS
// ═══════════════════════════════════════════════════════════════════════════════

async function getRevenueStats() {
  const times = getTimeRanges();
  
  // Today's revenue
  const { data: todayTx } = await supabase
    .from('stripe_transactions')
    .select('amount_usd, fee_usd')
    .eq('status', 'completed')
    .gte('completed_at', times.todayStart);
  
  const todayRevenue = todayTx?.reduce((sum, t) => sum + (t.fee_usd || t.amount_usd * 0.2), 0) || 0;
  const todayGMV = todayTx?.reduce((sum, t) => sum + t.amount_usd, 0) || 0;
  
  // This week
  const { data: weekTx } = await supabase
    .from('stripe_transactions')
    .select('amount_usd, fee_usd')
    .eq('status', 'completed')
    .gte('completed_at', times.weekStart);
  
  const weekRevenue = weekTx?.reduce((sum, t) => sum + (t.fee_usd || t.amount_usd * 0.2), 0) || 0;
  const weekGMV = weekTx?.reduce((sum, t) => sum + t.amount_usd, 0) || 0;
  
  // This month
  const { data: monthTx } = await supabase
    .from('stripe_transactions')
    .select('amount_usd, fee_usd')
    .eq('status', 'completed')
    .gte('completed_at', times.monthStart);
  
  const monthRevenue = monthTx?.reduce((sum, t) => sum + (t.fee_usd || t.amount_usd * 0.2), 0) || 0;
  const monthGMV = monthTx?.reduce((sum, t) => sum + t.amount_usd, 0) || 0;
  
  // All time
  const { data: allTx } = await supabase
    .from('stripe_transactions')
    .select('amount_usd, fee_usd')
    .eq('status', 'completed');
  
  const allTimeRevenue = allTx?.reduce((sum, t) => sum + (t.fee_usd || t.amount_usd * 0.2), 0) || 0;
  const allTimeGMV = allTx?.reduce((sum, t) => sum + t.amount_usd, 0) || 0;
  
  // Worker payouts (additional 20% from worker side)
  const { data: payouts } = await supabase
    .from('transactions')
    .select('amount')
    .eq('type', 'task_payment')
    .eq('status', 'completed')
    .gte('created_at', times.monthStart);
  
  const workerPayouts = payouts?.reduce((sum, p) => sum + p.amount, 0) || 0;
  const workerFees = workerPayouts * 0.2 / 0.8; // Calculate 20% fee from net payment
  
  return {
    today: { revenue: todayRevenue, gmv: todayGMV, transactions: todayTx?.length || 0 },
    week: { revenue: weekRevenue, gmv: weekGMV, transactions: weekTx?.length || 0 },
    month: { revenue: monthRevenue + workerFees, gmv: monthGMV, transactions: monthTx?.length || 0 },
    allTime: { revenue: allTimeRevenue, gmv: allTimeGMV, transactions: allTx?.length || 0 }
  };
}

// ═══════════════════════════════════════════════════════════════════════════════
// USER ANALYTICS
// ═══════════════════════════════════════════════════════════════════════════════

async function getUserStats() {
  const times = getTimeRanges();
  
  // Total users
  const { count: totalUsers } = await supabase
    .from('app_users')
    .select('id', { count: 'exact' });
  
  // New users today
  const { count: newToday } = await supabase
    .from('app_users')
    .select('id', { count: 'exact' })
    .gte('created_at', times.todayStart);
  
  // New users this week
  const { count: newWeek } = await supabase
    .from('app_users')
    .select('id', { count: 'exact' })
    .gte('created_at', times.weekStart);
  
  // Active users (activity in last 24h)
  const { count: activeDaily } = await supabase
    .from('app_users')
    .select('id', { count: 'exact' })
    .gte('last_active_at', times.yesterdayStart);
  
  // Workers vs Requesters
  const { count: workers } = await supabase
    .from('app_users')
    .select('id', { count: 'exact' })
    .eq('role', 'worker');
  
  const { count: requesters } = await supabase
    .from('app_users')
    .select('id', { count: 'exact' })
    .eq('role', 'requester');
  
  // Users with deposits
  const { count: depositingUsers } = await supabase
    .from('vae_balances')
    .select('id', { count: 'exact' })
    .gt('deposit_balance', 0);
  
  // Users with earnings
  const { count: earningUsers } = await supabase
    .from('vae_balances')
    .select('id', { count: 'exact' })
    .gt('earnings_balance', 0);
  
  return {
    total: totalUsers || 0,
    newToday: newToday || 0,
    newWeek: newWeek || 0,
    activeDaily: activeDaily || 0,
    workers: workers || 0,
    requesters: requesters || 0,
    withDeposits: depositingUsers || 0,
    withEarnings: earningUsers || 0
  };
}

// ═══════════════════════════════════════════════════════════════════════════════
// TASK ANALYTICS
// ═══════════════════════════════════════════════════════════════════════════════

async function getTaskStats() {
  const times = getTimeRanges();
  
  // Total tasks
  const { count: totalTasks } = await supabase
    .from('tasks')
    .select('id', { count: 'exact' });
  
  // Tasks posted today
  const { count: postedToday } = await supabase
    .from('tasks')
    .select('id', { count: 'exact' })
    .gte('created_at', times.todayStart);
  
  // Tasks completed today
  const { count: completedToday } = await supabase
    .from('submissions')
    .select('id', { count: 'exact' })
    .eq('status', 'approved')
    .gte('created_at', times.todayStart);
  
  // Active tasks
  const { count: activeTasks } = await supabase
    .from('tasks')
    .select('id', { count: 'exact' })
    .eq('status', 'active');
  
  // Pending submissions
  const { count: pendingSubmissions } = await supabase
    .from('submissions')
    .select('id', { count: 'exact' })
    .eq('status', 'pending');
  
  // Completion rate
  const { data: allSubmissions } = await supabase
    .from('submissions')
    .select('status')
    .gte('created_at', times.weekStart);
  
  const approved = allSubmissions?.filter(s => s.status === 'approved').length || 0;
  const total = allSubmissions?.length || 1;
  const completionRate = (approved / total * 100).toFixed(1);
  
  // Disputes
  const { count: openDisputes } = await supabase
    .from('disputes')
    .select('id', { count: 'exact' })
    .in('status', ['open', 'escalated']);
  
  return {
    total: totalTasks || 0,
    postedToday: postedToday || 0,
    completedToday: completedToday || 0,
    active: activeTasks || 0,
    pendingSubmissions: pendingSubmissions || 0,
    completionRate,
    openDisputes: openDisputes || 0
  };
}

// ═══════════════════════════════════════════════════════════════════════════════
// AI AUTOMATION STATS
// ═══════════════════════════════════════════════════════════════════════════════

async function getAutomationStats() {
  const times = getTimeRanges();
  
  // Moderation stats
  const { data: moderations } = await supabase
    .from('moderation_logs')
    .select('action')
    .gte('created_at', times.todayStart);
  
  const autoApproved = moderations?.filter(m => m.action === 'approve').length || 0;
  const autoRejected = moderations?.filter(m => m.action === 'reject').length || 0;
  const escalated = moderations?.filter(m => m.action === 'escalate').length || 0;
  
  // Dispute resolution
  const { data: disputes } = await supabase
    .from('disputes')
    .select('resolved_by')
    .eq('status', 'resolved')
    .gte('resolved_at', times.weekStart);
  
  const aiResolved = disputes?.filter(d => d.resolved_by === 'ai').length || 0;
  const humanResolved = disputes?.filter(d => d.resolved_by === 'human').length || 0;
  
  // Fraud detection
  const { count: fraudAlerts } = await supabase
    .from('fraud_alerts')
    .select('id', { count: 'exact' })
    .gte('created_at', times.weekStart);
  
  // Calculate automation rate
  const totalModerated = autoApproved + autoRejected + escalated;
  const moderationAutomation = totalModerated > 0 
    ? ((autoApproved + autoRejected) / totalModerated * 100).toFixed(1)
    : 0;
  
  const totalDisputes = aiResolved + humanResolved;
  const disputeAutomation = totalDisputes > 0
    ? (aiResolved / totalDisputes * 100).toFixed(1)
    : 0;
  
  // Estimate time saved (2 min per moderation, 15 min per dispute)
  const timeSavedMinutes = (autoApproved + autoRejected) * 2 + aiResolved * 15;
  
  return {
    moderation: {
      approved: autoApproved,
      rejected: autoRejected,
      escalated,
      automationRate: moderationAutomation
    },
    disputes: {
      aiResolved,
      humanResolved,
      automationRate: disputeAutomation
    },
    fraudAlerts: fraudAlerts || 0,
    timeSavedMinutes,
    timeSavedHours: (timeSavedMinutes / 60).toFixed(1)
  };
}

// ═══════════════════════════════════════════════════════════════════════════════
// COMPREHENSIVE DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════

async function getDashboard() {
  const [revenue, users, tasks, automation] = await Promise.all([
    getRevenueStats(),
    getUserStats(),
    getTaskStats(),
    getAutomationStats()
  ]);
  
  return {
    timestamp: new Date().toISOString(),
    revenue,
    users,
    tasks,
    automation
  };
}

/**
 * Generate dashboard text for Telegram
 */
async function getDashboardText() {
  const d = await getDashboard();
  
  let text = `📊 *LOOPUMAN DASHBOARD*\n`;
  text += `_${new Date().toLocaleString()}_\n\n`;
  
  // Revenue Section
  text += `💰 *REVENUE*\n`;
  text += `├ Today: $${d.revenue.today.revenue.toFixed(2)}\n`;
  text += `├ This Week: $${d.revenue.week.revenue.toFixed(2)}\n`;
  text += `├ This Month: $${d.revenue.month.revenue.toFixed(2)}\n`;
  text += `└ All Time: $${d.revenue.allTime.revenue.toFixed(2)}\n\n`;
  
  // Users Section
  text += `👥 *USERS*\n`;
  text += `├ Total: ${d.users.total.toLocaleString()}\n`;
  text += `├ Active (24h): ${d.users.activeDaily}\n`;
  text += `├ New Today: ${d.users.newToday}\n`;
  text += `├ Workers: ${d.users.workers}\n`;
  text += `└ Requesters: ${d.users.requesters}\n\n`;
  
  // Tasks Section
  text += `📋 *TASKS*\n`;
  text += `├ Active: ${d.tasks.active}\n`;
  text += `├ Posted Today: ${d.tasks.postedToday}\n`;
  text += `├ Completed Today: ${d.tasks.completedToday}\n`;
  text += `├ Pending Review: ${d.tasks.pendingSubmissions}\n`;
  text += `├ Completion Rate: ${d.tasks.completionRate}%\n`;
  text += `└ Open Disputes: ${d.tasks.openDisputes}\n\n`;
  
  // Automation Section
  text += `🤖 *AI AUTOMATION*\n`;
  text += `├ Moderation: ${d.automation.moderation.automationRate}%\n`;
  text += `├ Disputes: ${d.automation.disputes.automationRate}%\n`;
  text += `├ Fraud Alerts: ${d.automation.fraudAlerts}\n`;
  text += `└ Time Saved: ${d.automation.timeSavedHours}h\n`;
  
  return text;
}

// ═══════════════════════════════════════════════════════════════════════════════
// QUICK STATS (For bot inline buttons)
// ═══════════════════════════════════════════════════════════════════════════════

async function getQuickStats() {
  const times = getTimeRanges();
  
  const [
    { count: activeUsers },
    { count: activeTasks },
    { count: pendingDisputes }
  ] = await Promise.all([
    supabase.from('app_users').select('id', { count: 'exact' }).gte('last_active_at', times.yesterdayStart),
    supabase.from('tasks').select('id', { count: 'exact' }).eq('status', 'active'),
    supabase.from('disputes').select('id', { count: 'exact' }).in('status', ['open', 'escalated'])
  ]);
  
  return {
    activeUsers: activeUsers || 0,
    activeTasks: activeTasks || 0,
    pendingDisputes: pendingDisputes || 0
  };
}

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

module.exports = {
  // Individual stats
  getRevenueStats,
  getUserStats,
  getTaskStats,
  getAutomationStats,
  
  // Combined
  getDashboard,
  getDashboardText,
  getQuickStats,
  
  // Helpers
  getTimeRanges
};
