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

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger('HTTP');

  constructor(private readonly configService: ConfigService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    if (this.configService.get('app.nodeEnv') === 'production') {
      return next.handle();
    }

    const start = Date.now();
    const req = context.switchToHttp().getRequest();
    const method = req.method;
    const url = req.url || req.originalUrl || '?';

    return next.handle().pipe(
      tap({
        next: () => {
          const res = context.switchToHttp().getResponse();
          const duration = Date.now() - start;
          const logMsg = `${method} ${url} → ${res.statusCode} ${duration}ms`;
          if (res.statusCode >= 400) {
            this.logger.warn(logMsg);
          } else {
            this.logger.log(logMsg);
          }
        },
        error: (err) => {
          const duration = Date.now() - start;
          const msg = err?.message || err;
          this.logger.error(`${method} ${url} → ERR ${duration}ms - ${msg}`);
        },
      }),
    );
  }
}
