import { logger } from '@goodgo/logger';
import { Request, Response, NextFunction } from 'express';

import { getCorrelationId, getRequestId } from './correlation.middleware';

/**
 * EN: Enhanced request logger with correlation ID support
 * VI: Request logger nâng cao với hỗ trợ correlation ID
 */
export const requestLogger = (req: Request, res: Response, next: NextFunction): void => {
  // EN: Skip detailed logging for health checks and metrics (already logged by correlation middleware)
  // VI: Bỏ qua logging chi tiết cho health checks và metrics (đã được log bởi correlation middleware)
  if (req.path.startsWith('/health') || req.path.startsWith('/metrics')) {
    return next();
  }

  const start = Date.now();

  res.on('finish', () => {
    const duration = Date.now() - start;
    const correlationId = getCorrelationId(req);
    const requestId = getRequestId(req);

    logger.info('Request processed / Request đã xử lý', {
      correlationId,
      requestId,
      method: req.method,
      path: req.path,
      query: req.query,
      statusCode: res.statusCode,
      duration: `${duration}ms`,
      contentLength: res.get('Content-Length') || 0,
      userAgent: req.get('User-Agent'),
      ip: req.ip,
      userId: (req as any).user?.userId,
    });
  });

  next();
};
