/**
 * Compression utility functions for selective response compression
 * Only compresses when client sends x-compress: true header
 * Excludes images and binary files from compression to improve performance
 */

/**
 * List of content types that should not be compressed
 * These are typically binary files or already compressed formats
 */
const SKIP_COMPRESSION_TYPES = [
  'image/', // All image formats (jpeg, png, gif, webp, etc.)
  'video/', // All video formats
  'audio/', // All audio formats
  'application/zip', // ZIP archives
  'application/gzip', // GZIP files
  'application/x-rar', // RAR archives
  'application/pdf', // PDF documents
  'application/octet-stream', // Binary files
  'application/x-7z-compressed', // 7-Zip archives
  'application/x-tar', // TAR archives
  'application/vnd.ms-excel', // Excel files
  'application/vnd.openxmlformats', // Office documents
] as const;

/**
 * List of URL paths that should not be compressed
 * These typically serve static files or binary content
 */
const SKIP_COMPRESSION_PATHS = [
  '/uploads/', // User uploaded files
  '/static/', // Static assets
  '/assets/', // Asset files
  '/media/', // Media files
] as const;

/**
 * Determines if a response should be compressed based on content type and URL
 * @param contentType - The response content type
 * @param url - The request URL
 * @returns true if the response should be compressed, false otherwise
 */
export const shouldCompress = (
  contentType: string | undefined,
  url: string
): boolean => {
  // Skip compression for specific URL paths
  if (SKIP_COMPRESSION_PATHS.some(path => url.startsWith(path))) {
    return false;
  }

  // Skip compression for specific content types
  if (contentType) {
    if (SKIP_COMPRESSION_TYPES.some(type => contentType.includes(type))) {
      return false;
    }
  }

  // Compress text-based responses (JSON, HTML, CSS, JS, XML, etc.)
  return true;
};

/**
 * Configuration object for compression middleware
 */
export const compressionConfig = {
  level: 6, // Balanced compression level (1=fastest, 9=best compression)
  threshold: 1024, // Only compress responses larger than 1KB
  memLevel: 8, // Memory usage level (1=minimum, 9=maximum)
} as const;
