# Enable Brotli Compression for supported files, only if they exist
RewriteEngine On

# Serve .br files if the client supports Brotli
RewriteCond %{HTTP:Accept-Encoding} br
RewriteCond %{REQUEST_FILENAME}.br -f
RewriteRule ^(.*)$ $1.br [QSA,L]

# Set Content-Encoding header only for actual Brotli-compressed files
<FilesMatch "\.(js|css|html|json|svg|xml)\.br$">
    Header set Content-Encoding br
</FilesMatch>

# --------------------------------------------------
# Cache Control Headers
# --------------------------------------------------

# Never cache index.html - ensures users get new versions on reload
<Files "index.html">
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires "0"
</Files>

# Never cache build-info.json - used for update checks
<Files "build-info.json">
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires "0"
</Files>

# Cache versioned files forever (they have UUID in filename)
<FilesMatch "\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.(js|css|ttf)$">
    Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>

# Also cache brotli-compressed versioned files
<FilesMatch "\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.(js|css)\.br$">
    Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>

# --------------------------------------------------

# SPA fallback - route all non-file requests to index.html
# Note: We only skip files (!-f), not directories (!-d), because the SPA router
# needs to handle directory paths like /manuals/ even though that folder exists
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [L]