map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

server {
    listen 80;
    server_name _;

    # Use Docker's embedded DNS resolver so nginx re-resolves upstream hostnames
    # dynamically instead of caching IPs at startup (prevents 502 after container restarts).
    resolver 127.0.0.11 valid=10s ipv6=off;

    root /usr/share/nginx/html;
    index index.html;

    # Security headers (server-level -- inherited by all locations unless overridden)
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "0" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;

    # CSP for React SPA with Tailwind CSS and Leaflet maps
    # worker-src required for SRP key derivation Web Worker (Safari won't fall back to script-src)
    add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://*.tile.openstreetmap.org; font-src 'self'; connect-src 'self' ws: wss:; worker-src 'self'; frame-ancestors 'self'; base-uri 'self'; form-action 'self';" always;

    # Proxy API requests to the backend service
    # The api container is reachable via Docker internal DNS as "api" on port 8000
    location /api/ {
        # Use a variable so nginx applies the resolver on every request.
        # With a variable in proxy_pass, nginx passes the full request URI as-is
        # (no path stripping), so the upstream receives /api/... correctly.
        set $api_upstream api;
        proxy_pass http://$api_upstream:8000;
        proxy_http_version 1.1;
        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;
        # Disable buffering for streaming/SSE endpoints
        proxy_buffering off;
        proxy_read_timeout 300s;
        # Hide nginx server-level CSP — backend sets its own CSP on API responses
        proxy_hide_header Content-Security-Policy;
    }

    # WebSocket proxy for SSH terminal
    location /ws/ssh {
        resolver 127.0.0.11 valid=10s ipv6=off;
        set $poller_upstream http://poller:8080;

        proxy_pass $poller_upstream;
        proxy_http_version 1.1;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $host;

        proxy_read_timeout 1800s;
        proxy_send_timeout 1800s;

        proxy_buffering off;
        proxy_request_buffering off;
        proxy_busy_buffers_size 512k;
        proxy_buffers 8 512k;
    }

    # Proxy Xpra HTML5 client requests to the winbox-worker container
    location ~ ^/xpra/(\d+)/(.*) {
        resolver 127.0.0.11 valid=10s ipv6=off;
        set $xpra_port $1;
        set $xpra_path $2;
        set $worker_upstream winbox-worker;

        proxy_pass http://$worker_upstream:$xpra_port/$xpra_path$is_args$args;
        proxy_http_version 1.1;
        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 Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 300s;
        proxy_buffering off;
        # Xpra HTML5 client uses inline event handlers and eval — override the
        # strict server-level CSP.  Adding any add_header in a location block
        # replaces all inherited server-level add_header directives in nginx.
        add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval' ws: wss: data: blob:; frame-ancestors 'self';" always;
        add_header X-Content-Type-Options "nosniff" always;
    }

    # Serve static assets with long cache headers
    # Note: add_header in a location block clears parent-block headers,
    # so we re-add the essential security header for static assets.
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable" always;
        add_header X-Content-Type-Options "nosniff" always;
        try_files $uri =404;
    }

    # SPA routing: all other requests serve index.html
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Health check endpoint for container probes
    location /nginx-health {
        access_log off;
        return 200 "OK\n";
        add_header Content-Type text/plain;
    }
}
