import { pinoHttp } from 'pino-http';
import { logger } from './logger.js';

export function requestLog(options = {}) {
  return pinoHttp({
    logger,
    customLogLevel(req, res, err) {
      if (err || res.statusCode >= 500) return 'error';
      if (res.statusCode >= 400) return 'warn';
      return 'info';
    },
    customSuccessMessage(req, res) {
      return `${req.method} ${req.url} ${res.statusCode}`;
    },
    customErrorMessage(req, res, err) {
      return `${req.method} ${req.url} ${res.statusCode} ${err?.message ?? ''}`;
    },
    serializers: {
      req(req) {
        return {
          method: req.method,
          url: req.url,
          userId: req.raw?.user?.id ?? req.user?.id,
          ip: req.raw?.ip ?? req.ip,
        };
      },
      res(res) {
        return { statusCode: res.statusCode };
      },
    },
    ...options,
  });
}
