# /etc/apache2/sites-available/leafzine.conf
# Enable required modules first:
#   sudo a2enmod proxy proxy_http proxy_wstunnel rewrite headers ssl
#   sudo a2ensite leafzine
#   sudo systemctl reload apache2
#
# Then get SSL cert:
#   sudo certbot --apache -d leafzine.com -d www.leafzine.com

# ── HTTP → HTTPS redirect ─────────────────────────────────────────────────────
<VirtualHost *:80>
    ServerName  leafzine.com
    ServerAlias www.leafzine.com

    RewriteEngine On
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

# ── HTTPS — proxy to Node on localhost:8884 ───────────────────────────────────
<VirtualHost *:443>
    ServerName  leafzine.com
    ServerAlias www.leafzine.com

    # SSL (certbot fills these in automatically)
    SSLEngine on
    SSLCertificateFile    /etc/letsencrypt/live/leafzine.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/leafzine.com/privkey.pem
    Include               /etc/letsencrypt/options-ssl-apache.conf

    # Security headers
    Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "SAMEORIGIN"

    # ── WebSocket proxy (collab WS at /ws/collab) ────────────────────────────
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} websocket [NC]
    RewriteCond %{HTTP:Connection} upgrade  [NC]
    RewriteRule ^/?(.*) ws://localhost:8884/$1 [P,L]

    # ── HTTP proxy ───────────────────────────────────────────────────────────
    ProxyPreserveHost On
    ProxyRequests     Off

    ProxyPass        / http://localhost:8884/
    ProxyPassReverse / http://localhost:8884/

    # Forward real client IP to Express
    RequestHeader set X-Forwarded-Proto "https"
    RequestHeader set X-Forwarded-For   "%{REMOTE_ADDR}s"

    # Increase timeout for large file uploads (msg attachments up to 50 MB)
    ProxyTimeout 120

    ErrorLog  ${APACHE_LOG_DIR}/leafzine_error.log
    CustomLog ${APACHE_LOG_DIR}/leafzine_access.log combined
</VirtualHost>
