/**
 * Error Tracking Service - Main entry point with DI
 */

import type { ErrorTrackingAdapter, ErrorContext, ErrorTrackingConfig } from './interfaces';
import { GlitchTipAdapter } from './glitchtip-adapter';

export class ErrorTrackingService {
  private adapter: ErrorTrackingAdapter;

  constructor(adapter: ErrorTrackingAdapter) {
    this.adapter = adapter;
  }

  captureException(error: any, context?: ErrorContext): void {
    this.adapter.captureException(error, context);
  }

  captureMessage(message: string, context?: ErrorContext): void {
    this.adapter.captureMessage(message, context);
  }

  setUser(user: ErrorContext['user']): void {
    this.adapter.setUser(user);
  }

  setTag(key: string, value: string): void {
    this.adapter.setTag(key, value);
  }

  setExtra(key: string, value: any): void {
    this.adapter.setExtra(key, value);
  }
}

// Factory function
export function createGlitchTipErrorTracking(config: ErrorTrackingConfig): ErrorTrackingService {
  return new ErrorTrackingService(new GlitchTipAdapter(config));
}

// Default singleton
let defaultErrorTracking: ErrorTrackingService | null = null;

export function getDefaultErrorTracking(): ErrorTrackingService {
  if (!defaultErrorTracking) {
    defaultErrorTracking = createGlitchTipErrorTracking({
      dsn: process.env.NEXT_PUBLIC_GLITCHTIP_DSN || '',
      environment: process.env.NODE_ENV,
    });
  }
  return defaultErrorTracking;
}

// Convenience functions
export function captureException(error: any, context?: ErrorContext): void {
  getDefaultErrorTracking().captureException(error, context);
}

export function captureMessage(message: string, context?: ErrorContext): void {
  getDefaultErrorTracking().captureMessage(message, context);
}
