import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
import { v4 as uuidv4 } from 'uuid';

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

  use(req: Request, res: Response, next: () => void): void {
    // ここで一意のリクエストIDを生成して、リクエストヘッダーに設定する
    const requestId = uuidv4();
    req.headers['x-request-id'] = requestId;

    this.logger.log(this.createReqMsg(req));

    res.on('close', () => {
      this.logger.log(this.createResMsg(res));
    });
    next();
  }

  private createReqMsg(req: Request): string {
    const message = `[${req.header('x-request-id')}] Request [url=${
      req.url
    }, method=${req.method}]`;

    return message;
  }

  private createResMsg(res: Response): string {
    const message = `[${res.req.header('x-request-id')}] Response [statusCode=${
      res.statusCode
    }, message=${res.statusMessage}]`;

    return message;
  }
}
