worker_processes 1;

events { worker_connections 1024; }

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    map $http_x_forwarded_proto $proxy_x_forwarded_proto {
        default $http_x_forwarded_proto;
        ''      $scheme;
    }

    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    # Backend upstream
    upstream backend_service {
        server ai-hub:8000;
    }

    server {
        listen 80;
        server_name localhost;

        # Increase the max body size for audio uploads
        client_max_body_size 50M;

        # Frontend: Serve the static production build directly
        location / {
            root /usr/share/nginx/html;
            index index.html index.htm;
            try_files $uri /index.html;
        }

        # Backend: /api/v1 (proxied to the backend container)
        location /api/v1 {
            proxy_pass http://backend_service;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
            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 $proxy_x_forwarded_proto;

            # Streaming optimization
            proxy_buffering off;
            proxy_read_timeout 300s;
        }

        # Health check
        location /health {
            return 200 'OK';
        }
    }
}
