import { CreateOperationLogDto } from '@/modules/operation-log/dto/create-operation-log.dto';
import { OperationLogService } from '@/modules/operation-log/operation-log.service';
import { Inject, Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NextFunction, Request, Response } from 'express';

@Injectable()
export class HttpLoggerMiddleware implements NestMiddleware {
  constructor(
    @Inject(OperationLogService) private readonly operationLogService: OperationLogService,
  ) {}

  private logger = new Logger();

  use(request: any, response: Response, next: NextFunction): void {
    const { ip, method, originalUrl } = request;
    response.on('finish', () => {
      const msg = `${ip} ${method} ${originalUrl}`;
      this.logger.log(msg);
      if (request.user) {
        // console.log('userId', request.user.userId);
        const logDto: CreateOperationLogDto = {
          title: msg,
          requestUrl: originalUrl,
          ip: ip,
          method: method,
          userId: request.user.userId,
        };
        this.operationLogService.create(logDto);
        // console.log('operationLogService');
      }
    });

    next();
  }
}
