import { Injectable, type NestMiddleware } from '@nestjs/common';
import { type NextFunction, type Request, type Response } from 'express';
import { LoggerService } from '../logger.service';

@Injectable()
export class RequestLoggingMiddleware implements NestMiddleware {
  private readonly pinoChild;

  constructor(private readonly logger: LoggerService) {
    this.pinoChild = this.logger.child({ component: 'http' });
  }

  use(req: Request, res: Response, next: NextFunction): void {
    const start = Date.now();
    const correlationId = req.headers['x-correlation-id'] as string | undefined;

    res.on('finish', () => {
      const duration = Date.now() - start;
      const logData = {
        method: req.method,
        url: req.originalUrl,
        statusCode: res.statusCode,
        duration,
        correlationId,
        userAgent: req.headers['user-agent'],
        ip: req.ip,
      };

      if (res.statusCode >= 500) {
        this.pinoChild.error(logData, 'request completed');
      } else if (res.statusCode >= 400) {
        this.pinoChild.warn(logData, 'request completed');
      } else {
        this.pinoChild.info(logData, 'request completed');
      }
    });

    next();
  }
}
