# Log format to include request latency
log_format custom_main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for" '
                'rt=$request_time';

upstream api_server {
    # fail_timeout=0 means we always retry an upstream even if it failed
    # to return a good HTTP response

    # for UNIX domain socket setups
    #server unix:/tmp/gunicorn.sock fail_timeout=0;

    # for a TCP configuration
    # TODO: use gunicorn to manage multiple processes
    server api_server:8080 fail_timeout=0;
}

upstream web_server {
    server web_server:3000 fail_timeout=0;
}

server {
    listen 80;
    server_name ${DOMAIN};

    client_max_body_size 5G;    # Maximum upload size

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

    # Match both /api/* and /openapi.json in a single rule
    location ~ ^/(api|openapi.json)(/.*)?$ {
        # Rewrite /api prefixed matched paths
        rewrite ^/api(/.*)$ $1 break;

        # misc headers
        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 Host $host;

        # need to use 1.1 to support chunked transfers
        proxy_http_version 1.1;
        proxy_buffering off;

        # we don't want nginx trying to do something clever with
        # redirects, we set the Host: header above already.
        proxy_redirect off;
        proxy_pass http://api_server;
    }

    location / {
        # misc headers
        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 Host $host;

        proxy_http_version 1.1;

        # we don't want nginx trying to do something clever with
        # redirects, we set the Host: header above already.
        proxy_redirect off;
        proxy_pass http://web_server;
    }
}

server {
    listen 443 ssl;
    server_name ${DOMAIN};

    client_max_body_size 5G;    # Maximum upload size
    
    location / {
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_pass http://localhost:80;
    }

    ssl_certificate /etc/nginx/sslcerts/${SSL_CERT_FILE_NAME};
    ssl_certificate_key /etc/nginx/sslcerts/${SSL_CERT_KEY_FILE_NAME};
}
