# Maps the Upgrade header to the correct Connection value for WebSocket proxying.
# Lives at the http level (this file is included from nginx's http block).
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 8080;
    server_name _;
    root /usr/share/nginx/html;
    index index.html;

    # API + WebSocket routes are proxied to the backend container.
    # The frontend calls the API with relative paths (fetch('/api/...')), so
    # everything arrives on :8080 and nginx forwards /api to archnest-backend.
    # "archnest-backend" is the Docker Compose service name on the shared network.
    location /api/ {
        proxy_pass http://archnest-backend:4000;
        proxy_http_version 1.1;

        # WebSocket upgrade support (/api/terminal, /api/docker/exec,
        # /api/guacamole, /api/tunnels live data, etc.)
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;

        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;

        # Long-lived connections for terminals/tunnels/file transfers.
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
        proxy_buffering off;

        # Large file uploads via the file manager (backend allows up to 1GB).
        client_max_body_size 1024m;
    }

    # SPA fallback: serve index.html for client-side routes.
    location / {
        try_files $uri $uri/ /index.html;
    }
}
