events {
    worker_connections 1024;
}

http {
    client_max_body_size 500m;

    server {
        listen 80;
        server_name localhost;

        resolver 127.0.0.11 valid=5s;
        set $backend_upstream http://backend:8000;
        set $frontend_upstream http://frontend:80;

        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;
            }
        }

        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;
            proxy_request_buffering off;
        }

        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;
        }

        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;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }

    # Plain-HTTP-only host for ESP32 melody downloads. Kept separate from the
    # console.bellsystems.net server block above so console can stay HTTPS-only
    # in NPM with no path-based TLS exceptions. ESP32 devices can't afford the
    # RAM for a TLS client, so this host must never be forced to HTTPS upstream.
    server {
        listen 80;
        server_name melodies.bellsystems.net;

        resolver 127.0.0.11 valid=5s;
        set $backend_upstream http://backend:8000;

        location /download/ {
            rewrite ^/download/(.*)$ /api/melodies/download/$1 break;
            proxy_pass $backend_upstream$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;
        }
    }
}
