/**
 * Response Compression Middleware
 * High-performance compression with Brotli support
 */
const compression = require("compression");
const zlib = require("zlib");

const compressionMiddleware = compression({
  // Only compress responses larger than 512 bytes (lower threshold)
  threshold: 512,
  // Level 6 for gzip (balance between speed and ratio)
  level: 6,
  // Memory level
  memLevel: 8,
  // Use Brotli when available (better compression than gzip)
  brotli: {
    enabled: true,
    zlib: {
      [zlib.constants.BROTLI_PARAM_QUALITY]: 4, // 0-11, 4 is fast with good compression
      [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
    },
  },
  // Filter function - don't compress already compressed formats
  filter: (req, res) => {
    if (req.headers["x-no-compression"]) {
      return false;
    }

    const contentType = res.getHeader("Content-Type");
    if (!contentType) return compression.filter(req, res);

    // Don't compress images, videos, or already compressed formats
    const skipTypes = [
      "image/",
      "video/",
      "application/zip",
      "application/pdf",
      "application/octet-stream",
      "application/wasm",
      "font/",
    ];

    if (skipTypes.some((type) => contentType.includes(type))) {
      return false;
    }

    return compression.filter(req, res);
  },
});

module.exports = compressionMiddleware;
