/**
 * Error Monitoring Service (Sentry)
 * FREE tier: 5,000 errors/month
 * 
 * Setup: Add SENTRY_DSN to .env
 * Get DSN: https://sentry.io → Create Project → Node.js
 */
'use strict';

const Sentry = require('@sentry/node');

const isEnabled = !!process.env.SENTRY_DSN;

function init(serviceName) {
  if (!isEnabled) {
    console.log('[Sentry] Not configured - add SENTRY_DSN to .env');
    return;
  }
  
  Sentry.init({
    dsn: process.env.SENTRY_DSN,
    environment: process.env.NODE_ENV || 'production',
    serverName: serviceName,
    tracesSampleRate: 0.1, // 10% of transactions for performance
    beforeSend(event) {
      // Don't send user passwords/tokens
      if (event.request?.data) {
        delete event.request.data.password;
        delete event.request.data.token;
      }
      return event;
    }
  });
  
  console.log(`[Sentry] ✅ Initialized for ${serviceName}`);
}

function captureError(error, context = {}) {
  console.error('[Error]', error.message, context);
  if (isEnabled) {
    Sentry.captureException(error, { extra: context });
  }
}

function captureMessage(message, level = 'info', context = {}) {
  if (isEnabled) {
    Sentry.captureMessage(message, { level, extra: context });
  }
}

function setUser(userId, extra = {}) {
  if (isEnabled) {
    Sentry.setUser({ id: userId, ...extra });
  }
}

// Alert for critical business events
function alertCritical(event, data = {}) {
  const criticalEvents = [
    'withdrawal_failed',
    'blockchain_error', 
    'payment_mismatch',
    'enterprise_webhook_failed',
    'database_connection_lost'
  ];
  
  if (criticalEvents.includes(event)) {
    captureMessage(`🚨 CRITICAL: ${event}`, 'fatal', data);
  }
}

module.exports = {
  init,
  captureError,
  captureMessage,
  setUser,
  alertCritical,
  Sentry
};
