events {
    worker_connections 1024;
}

http {
    client_max_body_size 500m;

    server {
        listen 80;
        server_name localhost;

        # Use Docker's internal DNS so nginx re-resolves after container restarts
        resolver 127.0.0.11 valid=5s;
        set $backend_upstream http://backend:8000;
        set $frontend_upstream http://frontend:5173;

        # OTA firmware files — allow browser (esptool-js) to fetch .bin files directly
        location /ota/ {
            root /srv;
            add_header Access-Control-Allow-Origin "*";
            add_header Access-Control-Allow-Methods "GET, OPTIONS";
            add_header Access-Control-Allow-Headers "Authorization, Content-Type";
            if ($request_method = OPTIONS) {
                add_header Access-Control-Max-Age 3600;
                return 204;
            }
        }

        # API requests → FastAPI backend
        location /api/ {
            proxy_pass $backend_upstream$request_uri;
            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_read_timeout 300s;
            proxy_send_timeout 300s;
            # Do not buffer request bodies — stream them directly to backend.
            # Required for large file uploads (client_max_body_size 500m above).
            proxy_request_buffering off;
        }

        # WebSocket support for MQTT live data
        location /api/mqtt/ws {
            proxy_pass $backend_upstream$request_uri;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header Host $host;
        }

        # Everything else → React frontend (Vite dev server)
        location / {
            proxy_pass $frontend_upstream$request_uri;
            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;

            # WebSocket support for Vite HMR
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }

}
