// src/interceptors/logging.interceptor.ts
import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common';
import { ClsService } from 'nestjs-cls';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

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

  constructor(private readonly cls: ClsService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();

    const ip = this.cls.get('ip') || 'unknown';
    const countryCode = this.cls.get('countryCode') || 'unknown';
    const username = this.cls.get('email') || 'unknown';

    const method = request.method;
    const url = request.originalUrl;
    const start = Date.now();

    this.logger.log(`Entering ${method} ${url} from ${ip} (${countryCode})- User: ${username}`);

    return next.handle().pipe(
      tap(() => {
        const duration = Date.now() - start;
        let logMessage = `${method} ${url} - ${duration}ms - IP: ${ip} - User: ${username}`;

        if (method === 'POST' || method === 'PUT') {
          const body = JSON.stringify(request.body);
          logMessage += ` - Incoming Body: ${body}`;
        }

        this.logger.log(logMessage);
      }),
    );
  }
}
