import { logger } from '../services/logger.js';

export function requestLogger(req, res, next) {
  const start = Date.now();
  res.on('finish', () => {
    logger.info('request', {
      method: req.method,
      path: req.originalUrl,
      status: res.statusCode,
      durationMs: Date.now() - start,
      ip: req.ip,
      userId: req.user?.id || null,
      headers: redactHeaders(req.headers)
    });
  });
  next();
}

function redactHeaders(headers) {
  const safe = { ...headers };
  for (const key of ['authorization', 'cookie', 'set-cookie']) {
    if (safe[key]) safe[key] = '[redacted]';
  }
  return safe;
}
