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

    # SPA fallback — serve index.html for all non-file routes
    # Handles /s/{token} share links and other client-side routes
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Reverse proxy: PostgREST (Supabase client hits /rest/v1/*)
    location /rest/v1/ {
        proxy_pass http://rest:3000/;
        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;
    }

    # Reverse proxy: GoTrue auth (Supabase client hits /auth/v1/*)
    location /auth/v1/ {
        proxy_pass http://auth:9999/;
        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;
    }

    # Reverse proxy: Hocuspocus (WebSocket collaboration)
    location /ws/ {
        proxy_pass http://collab:4000/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header 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_read_timeout 86400;
    }

    # Cache static assets aggressively (hashed filenames)
    location /assets/ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # WASM files — correct MIME type + cache
    location /wasm/ {
        types { application/wasm wasm; }
        default_type application/javascript;
        expires 1y;
        add_header Cache-Control "public, immutable";
        add_header Cross-Origin-Embedder-Policy "require-corp";
        add_header Cross-Origin-Opener-Policy "same-origin";
    }

    # Gzip
    gzip on;
    gzip_types text/plain text/css application/javascript application/json application/wasm image/svg+xml;
    gzip_min_length 256;
}
