# WebSocket connection upgrade
map $http_upgrade $connection_upgrade {
  default upgrade;
  '' close;
}

upstream ${UPSTREAM_NAME} {
  server 127.0.0.1:${APP_PORT} fail_timeout=0;
}

server {
  listen 80;
  server_name ${SERVER_NAME};

  # Logs
  access_log /var/log/nginx/${SERVER_NAME}_access.log;
  error_log /var/log/nginx/${SERVER_NAME}_error.log;

  # All requests go through Phoenix (including static files)
  location / {
    proxy_pass http://${UPSTREAM_NAME};
    proxy_http_version 1.1;

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

    # WebSocket support
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

    # Timeouts
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 86400s; # Long timeout for WebSockets

    # Buffer settings
    proxy_buffering on;
    proxy_buffer_size 4k;
    proxy_buffers 8 4k;
    proxy_busy_buffers_size 8k;

    # File upload size
    client_max_body_size 10M;
  }

  # Deny access to hidden files
  location ~ /\. {
    deny all;
  }

  # Let's Encrypt challenge location
  location ~ /.well-known/acme-challenge {
    allow all;
  }
}
