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

events {
    worker_connections 1024;
    use epoll;
}

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;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    server_tokens off;

    # Client body size
    client_max_body_size {{ client_max_body }};

    # Gzip
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript 
               application/json application/javascript application/xml+rss 
               application/rss+xml font/truetype font/opentype 
               application/vnd.ms-fontobject image/svg+xml;

    # HSTS header
    {% if hsts_preload %}
    map $scheme $hsts_header {
        https "max-age=31536000; includeSubDomains; preload";
        default "";
    }
    {% else %}
    map $scheme $hsts_header {
        https "max-age=15768000; includeSubDomains";
        default "";
    }
    {% endif %}

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

    # Rate limit zones (defined globally)
    {% for zone_name, zone_def in rate_limit_zones.items() %}
    limit_req_zone $binary_remote_addr zone={{ zone_name }}:20m rate={{ zone_def }};
    {% endfor %}

    # Security headers (applied if enabled)
    {% if security_headers %}
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    {% endif %}

    # Include vhosts
    include /etc/nginx/conf.d/*.conf;
}
