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

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

  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const ctx = context.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();
    const startTime = Date.now();
    const { method, url } = request;

    this.logger.log(`→ ${method} ${url}`);

    return next.handle().pipe(
      tap(() => {
        this.logger.log(`← ${method} ${url} - ${response.statusCode} - ${Date.now() - startTime}ms`);
      }),
      catchError((error) => {
        this.logger.error(`← ${method} ${url} - ${error.status || 500} - ${Date.now() - startTime}ms - ${error.message}`);
        throw error;
      }),
    );
  }
}
