function logger(req, res, next) {
  req.requestId = Math.random().toString(36).substring(2, 10);
  console.log(JSON.stringify({
    timestamp: new Date().toISOString(),
    method: req.method,
    url: req.url,
    requestId: req.requestId,
    level: 'info',
    route: req.route ? req.route.path : 'unknown'
  }));
  res.on('finish', () => {
    const securityEvent = [401, 403].includes(res.statusCode);
    console.log(JSON.stringify({
      timestamp: new Date().toISOString(),
      method: req.method,
      url: req.url,
      status: res.statusCode,
      requestId: req.requestId,
      level: res.statusCode >= 400 ? 'error' : 'info',
      securityEvent: securityEvent,
      route: req.route ? req.route.path : 'unknown'
    }));
  });
  next();
}

module.exports = logger;