// import * as Sentry from '@sentry/node';

// Sentry configuration
export const SENTRY_CONFIG = {
  DSN: process.env.SENTRY_DSN,
  ENVIRONMENT: process.env.NODE_ENV || 'development',
  RELEASE: process.env.SENTRY_RELEASE || 'unknown',
  SAMPLE_RATE: process.env.NODE_ENV === 'production' ? 0.1 : 1.0,
  TRACES_SAMPLE_RATE: process.env.NODE_ENV === 'production' ? 0.1 : 1.0
};

// Initialize Sentry
if (SENTRY_CONFIG.DSN) {
  Sentry.init({
    dsn: SENTRY_CONFIG.DSN,
    environment: SENTRY_CONFIG.ENVIRONMENT,
    release: SENTRY_CONFIG.RELEASE,
    sampleRate: SENTRY_CONFIG.SAMPLE_RATE,
    tracesSampleRate: SENTRY_CONFIG.TRACES_SAMPLE_RATE,
    
    // Configure integrations
    integrations: [
      // HTTP integration for tracking HTTP requests
      new Sentry.Integrations.Http({ tracing: true }),
      
      // Express integration if using Express
      // new Sentry.Integrations.Express({ app }),
      
      // Database integration
      new Sentry.Integrations.Postgres(),
    ],

    // Configure beforeSend to filter sensitive data
    beforeSend(event, hint) {
      // Filter out sensitive information
      if (event.request) {
        // Remove sensitive headers
        if (event.request.headers) {
          delete event.request.headers['authorization'];
          delete event.request.headers['cookie'];
          delete event.request.headers['x-api-key'];
        }

        // Remove sensitive query parameters
        if (event.request.query_string) {
          const sensitiveParams = ['password', 'token', 'key', 'secret'];
          for (const param of sensitiveParams) {
            if (event.request.query_string.includes(param)) {
              event.request.query_string = event.request.query_string.replace(
                new RegExp(`${param}=[^&]*`, 'gi'),
                `${param}=[FILTERED]`
              );
            }
          }
        }
      }

      // Filter out sensitive data from breadcrumbs
      if (event.breadcrumbs) {
        event.breadcrumbs = event.breadcrumbs.map(breadcrumb => {
          if (breadcrumb.data) {
            const filteredData = { ...breadcrumb.data };
            for (const key in filteredData) {
              if (key.toLowerCase().includes('password') || 
                  key.toLowerCase().includes('token') ||
                  key.toLowerCase().includes('key') ||
                  key.toLowerCase().includes('secret')) {
                filteredData[key] = '[FILTERED]';
              }
            }
            breadcrumb.data = filteredData;
          }
          return breadcrumb;
        });
      }

      return event;
    },

    // Configure error filtering
    beforeBreadcrumb(breadcrumb, hint) {
      // Filter out noisy breadcrumbs
      if (breadcrumb.category === 'console' && breadcrumb.level === 'log') {
        return null;
      }
      
      return breadcrumb;
    }
  });

} else {
  // Sentry not configured - will use console logging instead
}

/**
 * Capture an exception with additional context
 */
export function captureException(error: Error, context?: {
  userId?: string;
  userEmail?: string;
  requestId?: string;
  additionalData?: Record<string, any>;
}) {
  if (!SENTRY_CONFIG.DSN) {

    return;
  }

  Sentry.withScope((scope) => {
    if (context?.userId) {
      scope.setUser({ id: context.userId, email: context.userEmail });
    }
    
    if (context?.requestId) {
      scope.setTag('requestId', context.requestId);
    }
    
    if (context?.additionalData) {
      scope.setContext('additional', context.additionalData);
    }
    
    Sentry.captureException(error);
  });
}

/**
 * Capture a message with additional context
 */
export function captureMessage(message: string, level: 'fatal' | 'error' | 'warning' | 'info' | 'debug' = 'info', context?: {
  userId?: string;
  userEmail?: string;
  requestId?: string;
  additionalData?: Record<string, any>;
}) {
  if (!SENTRY_CONFIG.DSN) {

    return;
  }

  Sentry.withScope((scope) => {
    if (context?.userId) {
      scope.setUser({ id: context.userId, email: context.userEmail });
    }
    
    if (context?.requestId) {
      scope.setTag('requestId', context.requestId);
    }
    
    if (context?.additionalData) {
      scope.setContext('additional', context.additionalData);
    }
    
    Sentry.captureMessage(message, level);
  });
}

/**
 * Track performance transactions
 */
export function startTransaction(name: string, operation: string = 'http') {
  if (!SENTRY_CONFIG.DSN) {
    return null;
  }

  return Sentry.startTransaction({
    name,
    op: operation
  });
}

/**
 * Set user context for current scope
 */
export function setUserContext(userId: string, userEmail?: string, userData?: Record<string, any>) {
  if (!SENTRY_CONFIG.DSN) {
    return;
  }

  Sentry.setUser({
    id: userId,
    email: userEmail,
    ...userData
  });
}

/**
 * Set additional context
 */
export function setContext(key: string, context: Record<string, any>) {
  if (!SENTRY_CONFIG.DSN) {
    return;
  }

  Sentry.setContext(key, context);
}

/**
 * Add breadcrumb for debugging
 */
export function addBreadcrumb(message: string, category: string = 'custom', level: 'fatal' | 'error' | 'warning' | 'info' | 'debug' = 'info', data?: Record<string, any>) {
  if (!SENTRY_CONFIG.DSN) {
    return;
  }

  Sentry.addBreadcrumb({
    message,
    category,
    level,
    data
  });
}

/**
 * Flush Sentry (useful for serverless environments)
 */
export async function flush(timeout: number = 2000): Promise<boolean> {
  if (!SENTRY_CONFIG.DSN) {
    return true;
  }

  return await Sentry.flush(timeout);
}

/**
 * Error boundary for API routes
 */
export function withSentry<T extends (...args: any[]) => any>(fn: T): T {
  return ((...args: any[]) => {
    try {
      const result = fn(...args);
      
      // Handle async functions
      if (result && typeof result.catch === 'function') {
        return result.catch((error: Error) => {
          captureException(error);
          throw error;
        });
      }
      
      return result;
    } catch (error) {
      captureException(error);
      throw error;
    }
  }) as T;
}

/**
 * Express middleware for Sentry (if needed)
 */
export function sentryRequestHandler() {
  if (!SENTRY_CONFIG.DSN) {
    return (req: any, res: any, next: any) => next();
  }

  return Sentry.Handlers.requestHandler();
}

export function sentryErrorHandler() {
  if (!SENTRY_CONFIG.DSN) {
    return (error: any, req: any, res: any, next: any) => next(error);
  }

  return Sentry.Handlers.errorHandler();
}

/**
 * Health check for Sentry
 */
export function healthCheck(): boolean {
  return !!SENTRY_CONFIG.DSN;
}

// Export Sentry instance for direct use
export { Sentry };