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

export default function requestLogger(
  req: Request,
  res: Response,
  next: NextFunction,
): void {
  const startedAt = performance.now();

  res.on('finish', () => {
    logger.debug('HTTP request', {
      method: req.method,
      path: req.originalUrl,
      statusCode: res.statusCode,
      durationMs: Math.round(performance.now() - startedAt),
      userId: req.currentUser?.id,
      role: req.currentUser?.app_role?.name,
      activeScope: req.currentUser?.activeScope,
    });
  });

  next();
}
