import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Logger,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

/**
 * Performance Monitoring Interceptor
 *
 * Logs execution time for all requests and tracks slow queries
 */
@Injectable()
export class PerformanceInterceptor implements NestInterceptor {
  private readonly logger = new Logger('PerformanceMonitor');
  private readonly slowQueryThreshold = 1000; // 1 second

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const { method, url } = request;
    const startTime = Date.now();

    return next.handle().pipe(
      tap(() => {
        const duration = Date.now() - startTime;

        // Log slow queries
        if (duration > this.slowQueryThreshold) {
          this.logger.warn(
            `Slow request detected: ${method} ${url} - ${duration}ms`,
          );
        }

        // Log all requests in development
        if (process.env.NODE_ENV === 'development') {
          this.logger.debug(`${method} ${url} - ${duration}ms`);
        }
      }),
    );
  }
}
