__DOGRAH_UPSTREAM_BLOCK__

server {
    listen 80;
    server_name __DOGRAH_PUBLIC_HOST__;

    # Redirect all HTTP to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name __DOGRAH_PUBLIC_HOST__;

    ssl_certificate     /etc/nginx/certs/local.crt;
    ssl_certificate_key /etc/nginx/certs/local.key;

    # Basic TLS settings
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    # Backend API and WebSockets - bypass the UI, go straight to the
    # api workers via the least_conn upstream defined above.
    location /api/v1/ {
        proxy_pass http://dograh_api;
        proxy_http_version 1.1;

        # Retry on a dead/restarting worker
        proxy_next_upstream error timeout http_502 http_503 http_504;

        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_set_header X-Forwarded-Proto https;

        # Long-lived WebSockets (audio streaming, signaling)
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;

        # Don't buffer streamed responses
        proxy_buffering off;
        client_max_body_size 100M;
    }

    location / {
        proxy_pass         http://ui:3010;
        proxy_http_version 1.1;

        # Important for WebSockets / hot reload etc.
        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_set_header X-Forwarded-Proto https;

        # Rewrite localhost MinIO URLs in API responses to use current domain
        sub_filter 'http://localhost:9000/voice-audio/' 'https://$host/voice-audio/';
        sub_filter_once off;
        sub_filter_types application/json text/html;
    }

    location /voice-audio/ {
        proxy_pass http://minio:9000/voice-audio/;

        proxy_http_version 1.1;

        # Headers for file downloads from MinIO
        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 https;

        # Allow large file downloads
        proxy_buffering off;
        client_max_body_size 100M;
    }
}
