// Logging Utility for Error Tracking and Monitoring
// Sentry entegrasyonu için hazır yapı

export enum LogLevel {
  DEBUG = 'debug',
  INFO = 'info',
  WARN = 'warn',
  ERROR = 'error',
  FATAL = 'fatal',
}

export interface LogContext {
  user?: {
    id: string;
    email?: string;
    role?: string;
  };
  request?: {
    url: string;
    method: string;
    headers?: Record<string, string>;
  };
  extra?: Record<string, any>;
}

class Logger {
  private isDevelopment = import.meta.env.DEV;
  private isSentryEnabled = false;

  constructor() {
    // Sentry'yi başlat (eğer yapılandırılmışsa)
    this.initSentry();
  }

  private initSentry() {
    // TODO: Sentry SDK'sını ekle ve yapılandır
    // import * as Sentry from '@sentry/react';
    // 
    // if (import.meta.env.VITE_SENTRY_DSN) {
    //   Sentry.init({
    //     dsn: import.meta.env.VITE_SENTRY_DSN,
    //     environment: import.meta.env.MODE,
    //     tracesSampleRate: 1.0,
    //   });
    //   this.isSentryEnabled = true;
    // }
  }

  private formatMessage(level: LogLevel, message: string, context?: LogContext): string {
    const timestamp = new Date().toISOString();
    const contextStr = context ? JSON.stringify(context, null, 2) : '';
    return `[${timestamp}] [${level.toUpperCase()}] ${message}\n${contextStr}`;
  }

  private sendToSentry(level: LogLevel, message: string, error?: Error, context?: LogContext) {
    if (!this.isSentryEnabled) return;

    // TODO: Sentry'ye gönder
    // if (error) {
    //   Sentry.captureException(error, {
    //     level: level as Sentry.SeverityLevel,
    //     contexts: {
    //       custom: context,
    //     },
    //   });
    // } else {
    //   Sentry.captureMessage(message, {
    //     level: level as Sentry.SeverityLevel,
    //     contexts: {
    //       custom: context,
    //     },
    //   });
    // }
  }

  debug(message: string, context?: LogContext) {
    if (this.isDevelopment) {
      console.debug(this.formatMessage(LogLevel.DEBUG, message, context));
    }
  }

  info(message: string, context?: LogContext) {
    console.info(this.formatMessage(LogLevel.INFO, message, context));
    this.sendToSentry(LogLevel.INFO, message, undefined, context);
  }

  warn(message: string, context?: LogContext) {
    console.warn(this.formatMessage(LogLevel.WARN, message, context));
    this.sendToSentry(LogLevel.WARN, message, undefined, context);
  }

  error(message: string, error?: Error, context?: LogContext) {
    console.error(this.formatMessage(LogLevel.ERROR, message, context), error);
    this.sendToSentry(LogLevel.ERROR, message, error, context);
  }

  fatal(message: string, error?: Error, context?: LogContext) {
    console.error(this.formatMessage(LogLevel.FATAL, message, context), error);
    this.sendToSentry(LogLevel.FATAL, message, error, context);
  }

  // Performans izleme
  startTransaction(name: string) {
    const startTime = performance.now();
    return {
      finish: () => {
        const duration = performance.now() - startTime;
        this.debug(`Transaction "${name}" took ${duration.toFixed(2)}ms`);
        // TODO: Sentry transaction
        // if (this.isSentryEnabled) {
        //   const transaction = Sentry.startTransaction({ name });
        //   transaction.finish();
        // }
      },
    };
  }

  // Breadcrumb ekleme (kullanıcı akışını takip için)
  addBreadcrumb(message: string, category: string, data?: Record<string, any>) {
    if (this.isDevelopment) {
      console.log(`[BREADCRUMB] [${category}] ${message}`, data);
    }
    // TODO: Sentry breadcrumb
    // if (this.isSentryEnabled) {
    //   Sentry.addBreadcrumb({
    //     message,
    //     category,
    //     data,
    //     level: 'info',
    //   });
    // }
  }

  // Kullanıcı context'i ayarla
  setUserContext(user: { id: string; email?: string; role?: string }) {
    // TODO: Sentry user context
    // if (this.isSentryEnabled) {
    //   Sentry.setUser({
    //     id: user.id,
    //     email: user.email,
    //     role: user.role,
    //   });
    // }
  }

  // Kullanıcı context'ini temizle
  clearUserContext() {
    // TODO: Sentry user context temizle
    // if (this.isSentryEnabled) {
    //   Sentry.setUser(null);
    // }
  }
}

// Singleton instance
export const logger = new Logger();

// React Error Boundary için helper
export function logReactError(error: Error, errorInfo: React.ErrorInfo) {
  logger.error('React Error Boundary yakaladı', error, {
    extra: {
      componentStack: errorInfo.componentStack,
    },
  });
}

// API hata logger
export function logApiError(
  endpoint: string,
  method: string,
  error: Error,
  statusCode?: number
) {
  logger.error(`API Hatası: ${method} ${endpoint}`, error, {
    request: {
      url: endpoint,
      method,
    },
    extra: {
      statusCode,
    },
  });
}

// Database hata logger
export function logDatabaseError(operation: string, table: string, error: Error) {
  logger.error(`Database Hatası: ${operation} on ${table}`, error, {
    extra: {
      operation,
      table,
    },
  });
}

// Auth hata logger
export function logAuthError(action: string, error: Error) {
  logger.error(`Auth Hatası: ${action}`, error, {
    extra: {
      action,
    },
  });
}

// Performance logger
export function logPerformance(metric: string, value: number, unit: string = 'ms') {
  logger.info(`Performance: ${metric} = ${value}${unit}`, {
    extra: {
      metric,
      value,
      unit,
    },
  });
}

// User action logger (analytics için)
export function logUserAction(action: string, data?: Record<string, any>) {
  logger.addBreadcrumb(action, 'user-action', data);
}

export default logger;
