const { getSupabaseServiceClient } = require('../utils/supabase');

async function recalculatePerformance(userId) {
  const supabase = getSupabaseServiceClient();

  // Fetch all settled bets for this user
  const { data: bets } = await supabase
    .from('bets')
    .select('amount, potential_payout, status, settled_at, placed_at')
    .eq('user_id', userId)
    .in('status', ['won', 'lost', 'push']);

  if (!bets || bets.length === 0) {
    return { weekly: null, monthly: null, all_time: null };
  }

  const now = new Date();
  const weekStart = getWeekStart(now);
  const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));

  const periods = {
    weekly: { start: weekStart },
    monthly: { start: monthStart },
    all_time: { start: new Date(0) },
  };

  const results = {};

  for (const [period, { start }] of Object.entries(periods)) {
    const periodBets = bets.filter((b) => {
      const settledAt = new Date(b.settled_at || b.placed_at);
      return settledAt >= start;
    });

    const stats = computeStats(periodBets);
    results[period] = stats;

    // Upsert into performance table
    await supabase.from('performance').upsert({
      user_id: userId,
      period,
      roi: stats.roi,
      win_rate: stats.win_rate,
      sample_size: stats.sample_size,
      total_wagered: stats.total_wagered,
      total_profit: stats.total_profit,
      calculated_at: now.toISOString(),
    }, {
      onConflict: 'user_id,period',
    });
  }

  return results;
}

function computeStats(bets) {
  if (bets.length === 0) {
    return { roi: 0, win_rate: 0, sample_size: 0, total_wagered: 0, total_profit: 0 };
  }

  let totalWagered = 0;
  let totalProfit = 0;
  let wonCount = 0;
  let lostCount = 0;

  for (const bet of bets) {
    const amount = parseFloat(bet.amount);
    const payout = parseFloat(bet.potential_payout || 0);

    totalWagered += amount;

    if (bet.status === 'won') {
      totalProfit += (payout - amount);
      wonCount++;
    } else if (bet.status === 'lost') {
      totalProfit -= amount;
      lostCount++;
    }
    // push: no profit change, not counted in win/loss
  }

  const sampleSize = bets.length;
  const roi = totalWagered > 0 ? Math.round((totalProfit / totalWagered) * 1000) / 10 : 0;
  const winRate = (wonCount + lostCount) > 0
    ? Math.round((wonCount / (wonCount + lostCount)) * 1000) / 10
    : 0;

  return {
    roi,
    win_rate: winRate,
    sample_size: sampleSize,
    total_wagered: Math.round(totalWagered * 100) / 100,
    total_profit: Math.round(totalProfit * 100) / 100,
  };
}

function getWeekStart(date) {
  const d = new Date(date);
  const day = d.getUTCDay();
  const diff = day === 0 ? 6 : day - 1; // Monday = 0
  d.setUTCDate(d.getUTCDate() - diff);
  d.setUTCHours(0, 0, 0, 0);
  return d;
}

module.exports = { recalculatePerformance, computeStats, getWeekStart };
