import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';

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

  use(req: Request, res: Response, next: NextFunction) {
    const start = Date.now();
    res.on('finish', () => {
      // const duration = Date.now() - start;
      // this.logger.log(`${req.method} ${req.url} - ${duration}ms`);
      const duration = Date.now() - start;
      let logMessage = `${req.method} ${req.url} - ${duration}ms`;

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

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