worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

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

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    sendfile on;
    keepalive_timeout 65;

    upstream gunicorn_h2 {
        server gunicorn-h2:8443;
        keepalive 32;
    }

    server {
        listen 8444 ssl;
        http2 on;
        server_name localhost;

        ssl_certificate /certs/server.crt;
        ssl_certificate_key /certs/server.key;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;

        # HTTP/2 settings
        http2_max_concurrent_streams 128;

        # Health check endpoint
        location /health {
            return 200 'OK';
            add_header Content-Type text/plain;
        }

        location / {
            # Proxy to gunicorn with HTTPS
            proxy_pass https://gunicorn_h2;
            proxy_http_version 1.1;
            proxy_ssl_verify off;
            proxy_ssl_server_name on;

            # Enable forwarding of 103 Early Hints from upstream
            # $http2 is set to "h2" when HTTP/2 is used, empty otherwise
            early_hints $http2;

            # Headers
            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_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Port $server_port;

            # Buffering settings
            proxy_buffering on;
            proxy_buffer_size 4k;
            proxy_buffers 8 4k;

            # Timeouts
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }
    }
}
