import type { Request, Response, NextFunction } from 'express';
import { logger } from '../utils/logger';
import { nanoid } from 'nanoid';

export function requestLogger(req: Request, res: Response, next: NextFunction): void {
  const requestId = nanoid(10);
  const startTime = Date.now();

  // Attach request ID
  req.headers['x-request-id'] = requestId;

  // Log request
  logger.info(
    {
      requestId,
      method: req.method,
      url: req.url,
      ip: req.ip,
      userAgent: req.get('user-agent'),
    },
    'Incoming request'
  );

  // Log response on finish
  res.on('finish', () => {
    const duration = Date.now() - startTime;
    logger.info(
      {
        requestId,
        method: req.method,
        url: req.url,
        statusCode: res.statusCode,
        duration,
      },
      'Request completed'
    );
  });

  next();
}
