# Specify the user under which nginx will run.
# This enhances security by not running as root.
# In our case, we are using the sqlpage user (created in the docker-compose.yml file)
# so that the NGINX worker processes can access the SQLPage socket.
user sqlpage;

# Set the number of worker processes. 'auto' detects the number of CPU cores.
# Alternative: Specific number like '4' for 4 worker processes.
worker_processes auto;

# Define the file where error logs will be written. 'notice' sets the logging level.
# Alternative levels: debug, info, warn, error, crit, alert, emerg
error_log /var/log/nginx/error.log notice;

# Specify the file where the main nginx process ID will be written
pid /var/run/nginx.pid;

# Configuration for connection processing
events {
    # Maximum number of simultaneous connections that can be opened by a worker process
    # Can be increased for high traffic sites, but limited by system resources
    worker_connections 1024;
}

# Main HTTP server configuration block
# In a typical configuration, you would have one http block for all your applications
# and each application would be defined in a different file, in the /etc/nginx/sites-available/ directory
# and then enabled by creating a symlink to it in the /etc/nginx/sites-enabled/ directory.
http {
    # This individual configuration files would start here, with only the contents
    # from inside the http block.

    # Include MIME types definitions file
    include /etc/nginx/mime.types;

    # Set the default MIME type if nginx can't determine it
    default_type application/octet-stream;

    # Define the format of the access log entries
    # This log format includes various details about each request
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    # Specify the file where access logs will be written, using the 'main' format defined above
    access_log /var/log/nginx/access.log main;

    # Enable the use of sendfile() for serving static files, which can improve performance
    sendfile on;

    # Set the timeout for keep-alive connections with the client
    # Can be adjusted based on your application's needs
    keepalive_timeout 65;

    # Define a rate limiting zone to protect against DDoS attacks
    # $binary_remote_addr uses less memory than $remote_addr
    # 10m defines the memory size for storing IP addresses
    # 1r/s sets the maximum rate of requests per second from a single IP
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    # Server block defining a virtual host
    server {
        # Listen on port 80 for HTTP connections
        # If you want to listen on port 443 for HTTPS, you can use the certbot command to get a certificate
        # and automatically configure NGINX to use it:
        # sudo certbot --nginx -d yourdomain.com
        listen 80;

        # Define the server name. 'localhost' is used here, but should be your domain in production
        # server_name yourdomain.com;
        server_name localhost;

        # Configuration for serving static files
        # Note the trailing slash in the location block
        # It is necessary because we want to serve files from /var/www/static/
        # and we want to allow users to request http://localhost/static/foo.js
        # as well as http://localhost/static/dir/bar.js
        location /static/ {
            # Set the directory from which static files will be served
            # This allows you to place static files in the `website/static/` directory
            # and serve them at http://localhost:80/static/...
            # This removes load from the SQLPage application that will only handle dynamic requests
            alias /var/www/static/;
        }

        # Configuration for proxying requests to SQLPage
        location / {
            # Apply rate limiting to this location
            # burst=5 allows temporary bursts of requests
            # This is useful to avoid DoS attacks
            limit_req zone=one burst=5;

            # URL rewriting example for pretty URLs
            # Rewrites /post/123 to /post.sql?id=123
            rewrite ^/post/([0-9]+)$ /post.sql?id=$1 last;

            # Proxy requests to a Unix socket where SQLPage is listening
            proxy_pass http://unix:/tmp/sqlpage/sqlpage.sock;

            # Set headers for the proxied request
            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;

            # Enable caching of proxied content
            # Cache successful responses for 60 minutes and 404 responses for 10 minutes
            proxy_cache_valid 200 60m;
            proxy_cache_valid 404 10m;

            # Use stale cached content when upstream errors occur
            proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;

            # Enable buffering of responses from the proxied server
            proxy_buffering on;

            # Set the size of the buffer used for reading the first part of the response
            proxy_buffer_size 128k;

            # Set the number and size of buffers used for reading a response
            proxy_buffers 4 256k;

            # Limit the amount of data that can be stored in buffers while a response is being processed
            proxy_busy_buffers_size 256k;
        }
    }
}