# SPA routing for Apache/cPanel: serve real files/assets as-is, and send every
# other path to index.html so the Next.js client router can handle it (no 404 on refresh).
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Force https. This origin serves the JS that handles the password, so it must be TLS too.
    # The X-Forwarded-Proto condition prevents a redirect loop when TLS terminates at a proxy.
    # Needs an AutoSSL cert on this subdomain first; on a cert-less demo host delete these three lines.
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP:X-Forwarded-Proto} !=https
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    # TODO-099: the customer portal is its own static build in portal/ (https://{company}.<domain>/portal/, own .htaccess).
    # Never hand /portal/* to this SPA's fallback — portal/.htaccess serves its pages, a missing file is a plain 404.
    RewriteRule ^portal(/.*)?$ - [L]

    # Don't rewrite real files or directories (assets, config.js, the exported page folders, etc.)
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]

    # A route exported as its own folder (trailingSlash) — /dashboard → /dashboard/index.html
    RewriteCond %{DOCUMENT_ROOT}/$1/index.html -f
    RewriteRule ^([^.]+?)/?$ /$1/index.html [L]

    # Everything else → the SPA entry point
    RewriteRule ^ index.html [L]
</IfModule>

# Long-cache the fingerprinted build assets; never cache config.js or index.html.
<IfModule mod_headers.c>
    Header always set Strict-Transport-Security "max-age=31536000" env=HTTPS
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "DENY"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    <If "%{REQUEST_URI} =~ m#^/_next/static/#">
        Header set Cache-Control "public, max-age=31536000, immutable"
    </If>
    <FilesMatch "\.(woff2?|svg|png|jpg|jpeg|gif|ico)$">
        Header set Cache-Control "public, max-age=31536000, immutable"
    </FilesMatch>
    <FilesMatch "(index\.html|config\.js|sw\.js)$">
        Header set Cache-Control "no-cache, must-revalidate"
    </FilesMatch>
</IfModule>

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json image/svg+xml
</IfModule>
