import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { ClsService } from 'nestjs-cls';
import { getRealIpInfo } from 'src/utils/ip.util';

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

  constructor(private readonly cls: ClsService) {}

  use(req: Request, res: Response, next: NextFunction) {
    const { ip, countryCode } = getRealIpInfo(req);

    // Setze die IP-Adresse und den Ländercode im CLS-Kontext
    try {
      this.cls.set('ip', ip);
      this.cls.set('countryCode', countryCode);
    } catch (error) {
      this.logger.error('Failed to set CLS context', error);
    }

    // const start = Date.now();

    // this.logger.log(`Entering ${req.method} ${req.originalUrl} from ${ip}`);

    // res.on('finish', () => {
    //   const duration = Date.now() - start;
    //   const userEmail = this.cls.get('userEmail') || 'unknown';
    //   let logMessage = `${req.method} ${req.originalUrl} - ${duration}ms - IP: ${ip} - User: ${userEmail}`;

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

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

    next();
  }
}
