worker_processes auto;
events { worker_connections 1024; }

http {
  sendfile on;
  include       mime.types;
  default_type  application/octet-stream;
  log_format main '$remote_addr - $host "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
  access_log /dev/stdout main;
  error_log  /dev/stderr warn;

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

  # Upstreams (internal)
  upstream api_upstream    { server 127.0.0.1:5000; }
  upstream flet_upstream   { server 127.0.0.1:8080; }

  server {
    listen 80 default_server;
    server_name _;

    # API at /api -> Flask (gunicorn)
    location /api/ {
      proxy_set_header Host $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $x_proto_pass;
      proxy_set_header X-Forwarded-Host   $host;
      proxy_pass http://api_upstream/;
    }

    # Everything else -> Flet web app
    location / {
      proxy_set_header Host $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $x_proto_pass;
      proxy_set_header X-Forwarded-Host   $host;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection $connection_upgrade;
      proxy_pass http://flet_upstream;
    }
  }

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