import { log, fmtDuration, fmtStatus, fmtMethod } from '../config/logger.js';

export default function requestResponseLogger(req, res, next) {
  const start = Date.now();
  const { method, originalUrl } = req;

  res.on('finish', () => {
    try {
      const duration = Date.now() - start;
      const status = res.statusCode;
      const contentType = (res.getHeader?.('content-type') || '').toString().toLowerCase();
      const format = contentType.includes('json') ? 'json' : contentType.includes('html') ? 'html' : '';
      const formatStr = format ? ` ${format}` : '';

      // METHOD /path → status (duration)
      log.http.info(
        `${fmtMethod(method)} ${originalUrl} → ${fmtStatus(status)}${formatStr} (${fmtDuration(duration)})`
      );
    } catch {
      // never break the request pipeline
    }
  });

  return next();
}
