/**
 * Simple Analytics Service
 * Tracks key events in Supabase - no external service needed
 */
'use strict';
require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

const analytics = {
  async track(userId, event, properties = {}) {
    try {
      await supabase.from('analytics_events').insert({
        user_id: userId,
        event,
        properties,
        platform: properties.platform || 'telegram',
        created_at: new Date().toISOString()
      });
    } catch (e) { /* silent fail */ }
  },

  // Key Events
  signup: (userId, platform, referrer) => analytics.track(userId, 'signup', { platform, referrer }),
  taskCreated: (userId, taskId, category, budget) => analytics.track(userId, 'task_created', { taskId, category, budget }),
  taskAccepted: (userId, taskId, category) => analytics.track(userId, 'task_accepted', { taskId, category }),
  taskSubmitted: (userId, taskId, timeToComplete) => analytics.track(userId, 'task_submitted', { taskId, timeToComplete }),
  taskApproved: (userId, taskId, earnings) => analytics.track(userId, 'task_approved', { taskId, earnings }),
  withdrawal: (userId, amount, token, txHash) => analytics.track(userId, 'withdrawal', { amount, token, txHash }),
  deposit: (userId, amount, token) => analytics.track(userId, 'deposit', { amount, token }),
  featureUsed: (userId, feature) => analytics.track(userId, 'feature_used', { feature }),

  // Aggregation queries
  async getDailyStats(date) {
    const startOfDay = new Date(date).toISOString().split('T')[0];
    const { data } = await supabase.from('analytics_events')
      .select('event')
      .gte('created_at', startOfDay + 'T00:00:00Z')
      .lte('created_at', startOfDay + 'T23:59:59Z');
    
    const counts = {};
    (data || []).forEach(e => { counts[e.event] = (counts[e.event] || 0) + 1; });
    return counts;
  },

  async getRetention(days = 7) {
    const cutoff = new Date(Date.now() - days * 86400000).toISOString();
    const { data } = await supabase.from('analytics_events')
      .select('user_id, created_at')
      .gte('created_at', cutoff);
    
    const userDays = {};
    (data || []).forEach(e => {
      const day = e.created_at.split('T')[0];
      if (!userDays[e.user_id]) userDays[e.user_id] = new Set();
      userDays[e.user_id].add(day);
    });
    
    const retention = {};
    Object.values(userDays).forEach(days => {
      const count = days.size;
      retention[count] = (retention[count] || 0) + 1;
    });
    return retention;
  }
};

module.exports = analytics;
