import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { LoggingService } from '../common/config/logging.service';

@Injectable()
export class LoggingMiddleware implements NestMiddleware {
  constructor(private readonly loggingService: LoggingService) { }

  use(req: Request, res: Response, next: NextFunction) {
    const { method, originalUrl, body } = req;
    const start = Date.now();

    // res.on('finish', () => {
    const { statusCode } = res;
    const end = Date.now();
    const duration = end - start;
    const logMessage = `${req.ip} : ${method} : ${originalUrl} : Status Code :: ${statusCode} - ${duration}ms - Body : ${JSON.stringify(body)}`;

    this.loggingService.log(logMessage);
    // });

    next();
  }
}
