# HTTP server block - redirect to HTTPS
server {
    listen 80;
    server_name vhtv-stiftung.de www.vhtv-stiftung.de;

    # Redirect all HTTP traffic to HTTPS
    return 301 https://$server_name$request_uri;
}

# HTTPS server block
server {
    listen 443 ssl http2;
    server_name vhtv-stiftung.de www.vhtv-stiftung.de;

    # SSL Certificate Configuration
    ssl_certificate /etc/letsencrypt/live/vhtv-stiftung.de/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/vhtv-stiftung.de/privkey.pem;

    # SSL Security Settings
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # HSTS (HTTP Strict Transport Security)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # Enhanced Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' https: data: blob: 'unsafe-inline'" always;

    # Static files
    location /static/ {
        alias /opt/stiftung/app/static/;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    location /media/ {
        alias /opt/stiftung/app/media/;
        expires 1y;
        add_header Cache-Control "public";
    }

    # Django application
    location / {
        proxy_pass http://127.0.0.1:8081;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # Buffer settings
        proxy_buffering on;
        proxy_buffer_size 128k;
        proxy_buffers 4 256k;
        proxy_busy_buffers_size 256k;
    }

    # Paperless-ngx document management
    location /paperless/ {
        proxy_pass http://127.0.0.1:8080/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Script-Name /paperless;

        # Large file uploads for documents
        client_max_body_size 100M;
        proxy_read_timeout 300s;
        proxy_connect_timeout 300s;
        proxy_send_timeout 300s;
    }

    # GrampsWeb: fix double fonts/ path from CSS relative URL resolution
    # fonts.css at /ahnenforschung/fonts/ references url('fonts/file.woff2')
    # which resolves to /ahnenforschung/fonts/fonts/file.woff2
    location /ahnenforschung/fonts/fonts/ {
        proxy_pass http://127.0.0.1:8090/fonts/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # GrampsWeb Ahnenforschung
    # All path rewriting happens here via sub_filter — no container-side patching needed.
    # GrampsWeb SPA uses Vaadin Router with absolute paths; the injected History API
    # interceptor ensures pushState/replaceState calls get the /ahnenforschung/ prefix,
    # while <base href> lets the router strip it back for route matching.
    location /ahnenforschung/ {
        proxy_pass http://127.0.0.1:8090/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Script-Name /ahnenforschung;

        # Disable upstream compression so sub_filter can operate on response bodies
        proxy_set_header Accept-Encoding "";

        # Apply sub_filter to HTML, JS, and CSS responses
        sub_filter_types application/javascript text/javascript text/css;
        sub_filter_once off;

        # HTML: set <base href> so the SPA router knows its prefix
        sub_filter '<base href="/">' '<base href="/ahnenforschung/">';

        # HTML: inject History API interceptor — ensures pushState/replaceState
        # always include the /ahnenforschung/ prefix for correct SPA routing on reload
        sub_filter '</head>' '<script>!function(){var p="/ahnenforschung",o=history.pushState,r=history.replaceState;function w(u){return"string"==typeof u&&"/"===u[0]&&0!==u.indexOf(p)?p+u:u}history.pushState=function(s,t,u){return o.call(this,s,t,w(u))},history.replaceState=function(s,t,u){return r.call(this,s,t,w(u))}}();</script></head>';

        # JS: rewrite hardcoded absolute API/resource paths
        sub_filter '"/api/' '"/ahnenforschung/api/';
        sub_filter '`/api/' '`/ahnenforschung/api/';
        sub_filter '"/lang/' '"/ahnenforschung/lang/';
        sub_filter '`/lang/' '`/ahnenforschung/lang/';
        sub_filter '"/fonts/' '"/ahnenforschung/fonts/';
        sub_filter '`/fonts/' '`/ahnenforschung/fonts/';
        sub_filter '"/assets/' '"/ahnenforschung/assets/';
        sub_filter '`/assets/' '`/ahnenforschung/assets/';

        # JS: rewrite root redirects
        sub_filter 'location.href="/"' 'location.href="/ahnenforschung/"';
        sub_filter 'document.location.href="/"' 'document.location.href="/ahnenforschung/"';

        # JS: service worker route handling
        sub_filter 'createHandlerBoundToURL("/index.html")' 'createHandlerBoundToURL("/ahnenforschung/index.html")';

        # CSS font paths: handled by separate location block for /ahnenforschung/fonts/fonts/

        # WebSocket support
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_read_timeout 300s;
        proxy_connect_timeout 60s;
        proxy_send_timeout 300s;
    }

    # Health check endpoint
    location /health/ {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }

    # Block access to sensitive files
    location ~ /\. {
        deny all;
    }

    location ~ ^/(\.env|docker-compose|Dockerfile) {
        deny all;
    }
}
