/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * LOOPUMAN - DASHBOARD METRICS SERVICE
 * Fixed: 9 February 2026
 * ═══════════════════════════════════════════════════════════════════════════════
 *
 * Real-time stats for admin monitoring.
 *
 * FIXES APPLIED:
 *  - Bug 17 (MEDIUM): getGrowth() now uses single RPC query instead of N+1
 *  - Bug 19 (LOW):    weeklyVolume excludes withdrawals (only task_payment)
 *  - Bug 20 (LOW):    Added 60-second TTL cache for overview
 *
 * ═══════════════════════════════════════════════════════════════════════════════
 */
'use strict';
require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

// Simple in-memory cache with TTL
const cache = {};
const CACHE_TTL_MS = 60_000; // 60 seconds

function getCached(key) {
  const entry = cache[key];
  if (entry && Date.now() - entry.ts < CACHE_TTL_MS) return entry.data;
  return null;
}

function setCache(key, data) {
  cache[key] = { data, ts: Date.now() };
}

const dashboard = {

  async getOverview() {
    const cached = getCached('overview');
    if (cached) return cached;

    const now = new Date();
    const today = now.toISOString().split('T')[0];
    const weekAgo = new Date(now - 7 * 86400000).toISOString();

    const [users, tasks, subs, txs, volume] = await Promise.all([
      supabase.from('app_users').select('id', { count: 'exact', head: true }),
      supabase.from('tasks').select('id, status', { count: 'exact' }),
      supabase.from('submissions').select('id', { count: 'exact', head: true }),
      supabase.from('transactions').select('id', { count: 'exact', head: true }).gte('created_at', today),
      // Bug 19 fix: only count task_payment, not withdrawals
      supabase.from('transactions').select('amount').eq('type', 'task_payment').gte('created_at', weekAgo),
    ]);

    const weeklyVolume = (volume.data || []).reduce((sum, t) => sum + (t.amount || 0), 0);

    const result = {
      totalUsers: users.count || 0,
      totalTasks: tasks.count || 0,
      openTasks: (tasks.data || []).filter(t => t.status === 'open').length,
      totalSubmissions: subs.count || 0,
      todayTransactions: txs.count || 0,
      weeklyVolume,
      timestamp: now.toISOString()
    };

    setCache('overview', result);
    return result;
  },

  /**
   * Get 7-day user growth.
   * Bug 17 fix: Single query fetching all users from last 7 days,
   * then groups client-side. Falls back to cumulative count if needed.
   */
  async getGrowth() {
    const days = [];
    const sevenDaysAgo = new Date(Date.now() - 6 * 86400000).toISOString().split('T')[0];

    // Fetch signups from last 7 days in one query
    const { data: recentUsers } = await supabase
      .from('app_users')
      .select('created_at')
      .gte('created_at', sevenDaysAgo + 'T00:00:00Z')
      .order('created_at', { ascending: true });

    // Group by date
    const signupsByDate = {};
    for (const u of (recentUsers || [])) {
      const date = u.created_at.split('T')[0];
      signupsByDate[date] = (signupsByDate[date] || 0) + 1;
    }

    // Build 7-day array
    for (let i = 6; i >= 0; i--) {
      const date = new Date(Date.now() - i * 86400000).toISOString().split('T')[0];
      days.push({
        date,
        new_users: signupsByDate[date] || 0
      });
    }

    return days;
  },

  async getTopWorkers(limit = 10) {
    const { data } = await supabase.from('app_users')
      .select('id, username, first_name, tasks_completed, trust_score, total_earned')
      .order('tasks_completed', { ascending: false })
      .limit(limit);
    return data || [];
  },

  async getRecentActivity(limit = 20) {
    const { data } = await supabase.from('transactions')
      .select('*, user:app_users(username, first_name)')
      .order('created_at', { ascending: false })
      .limit(limit);
    return data || [];
  }
};

module.exports = dashboard;
