/**
 * LOOPUMAN MONITORING SERVICE
 * Error tracking, analytics, and alerting
 */
'use strict';
const Sentry = require('@sentry/node');

// Initialize Sentry (get free DSN from sentry.io)
const SENTRY_DSN = process.env.SENTRY_DSN || '';

if (SENTRY_DSN) {
  Sentry.init({
    dsn: SENTRY_DSN,
    environment: process.env.NODE_ENV || 'production',
    tracesSampleRate: 0.1, // 10% of transactions for performance
  });
  console.log('✅ Sentry initialized');
} else {
  console.log('⚠️ Sentry DSN not set - error monitoring disabled');
}

// Simple analytics tracking (stored in Supabase)
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

const analytics = {
  // Track event
  async track(userId, event, properties = {}) {
    try {
      await supabase.from('analytics_events').insert({
        user_id: userId,
        event,
        properties,
        created_at: new Date().toISOString(),
      });
    } catch (e) {
      console.error('Analytics error:', e.message);
    }
  },

  // Track key events
  async userSignup(userId, source) {
    await this.track(userId, 'user_signup', { source });
  },
  async taskCreated(userId, taskId, category, budget) {
    await this.track(userId, 'task_created', { task_id: taskId, category, budget });
  },
  async taskAccepted(userId, taskId) {
    await this.track(userId, 'task_accepted', { task_id: taskId });
  },
  async taskCompleted(userId, taskId, earnings) {
    await this.track(userId, 'task_completed', { task_id: taskId, earnings });
  },
  async withdrawal(userId, amount, token) {
    await this.track(userId, 'withdrawal', { amount, token });
  },
  async deposit(userId, amount, token) {
    await this.track(userId, 'deposit', { amount, token });
  },
};

// Error capture
const captureError = (error, context = {}) => {
  console.error('Error:', error.message, context);
  if (SENTRY_DSN) {
    Sentry.captureException(error, { extra: context });
  }
};

// Health check endpoint data
const getHealthMetrics = async () => {
  const now = new Date();
  const today = new Date(now.setHours(0, 0, 0, 0)).toISOString();
  
  const [users, tasks, submissions, transactions] = await Promise.all([
    supabase.from('app_users').select('id', { count: 'exact' }),
    supabase.from('tasks').select('id', { count: 'exact' }).eq('status', 'open'),
    supabase.from('submissions').select('id', { count: 'exact' }).gte('created_at', today),
    supabase.from('transactions').select('id', { count: 'exact' }).gte('created_at', today),
  ]);

  return {
    total_users: users.count || 0,
    open_tasks: tasks.count || 0,
    submissions_today: submissions.count || 0,
    transactions_today: transactions.count || 0,
    timestamp: new Date().toISOString(),
  };
};

module.exports = { analytics, captureError, getHealthMetrics, Sentry };
