# ==============================================================================
# NGINX MAIN CONFIGURATION FOR ADTLAS
# ==============================================================================
# 
# High-performance Nginx configuration optimized for the Adtlas TV advertising
# platform. This configuration provides reverse proxy functionality, static
# file serving, security headers, and performance optimizations.
#
# Features:
# - Reverse proxy to Django application
# - Static and media file serving
# - Security headers and SSL termination
# - Performance optimizations
# - Load balancing capabilities
# - Comprehensive logging
#
# Author: Adtlas Development Team
# Version: 1.0.0
# Nginx Version: 1.24+
# Last Updated: 2025-07-08
# ==============================================================================

# ==============================================================================
# GLOBAL CONFIGURATION
# ==============================================================================

# Run as nginx user (default in Alpine)
user nginx;

# Number of worker processes (auto-detect CPU cores)
worker_processes auto;

# Maximum number of open files per worker
worker_rlimit_nofile 65535;

# Error log configuration
error_log /var/log/nginx/error.log warn;

# Process ID file
pid /var/run/nginx.pid;

# ==============================================================================
# EVENTS CONFIGURATION
# ==============================================================================
events {
    # Use epoll for better performance on Linux
    use epoll;
    
    # Maximum number of connections per worker
    worker_connections 4096;
    
    # Accept multiple connections at once
    multi_accept on;
    
    # Accept connections as fast as possible
    accept_mutex off;
}

# ==============================================================================
# HTTP CONFIGURATION
# ==============================================================================
http {
    # ===========================================================================
    # MIME TYPES AND CHARACTER ENCODING
    # ===========================================================================
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    charset utf-8;
    
    # ===========================================================================
    # LOGGING CONFIGURATION
    # ===========================================================================
    
    # Custom log format with additional information
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for" '
                    'rt=$request_time uct="$upstream_connect_time" '
                    'uht="$upstream_header_time" urt="$upstream_response_time"';
    
    # Enhanced log format for debugging
    log_format debug '$remote_addr - $remote_user [$time_local] "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for" '
                     'rt=$request_time uct="$upstream_connect_time" '
                     'uht="$upstream_header_time" urt="$upstream_response_time" '
                     'cs=$upstream_cache_status';
    
    # Access log configuration
    access_log /var/log/nginx/access.log main;
    
    # ===========================================================================
    # PERFORMANCE OPTIMIZATIONS
    # ===========================================================================
    
    # Enable sendfile for efficient file serving
    sendfile on;
    
    # Send headers and file content in one packet
    tcp_nopush on;
    
    # Don't buffer data-sends (disable Nagle algorithm)
    tcp_nodelay on;
    
    # Timeout for keep-alive connections
    keepalive_timeout 65;
    keepalive_requests 1000;
    
    # Timeout for client connections
    client_body_timeout 12;
    client_header_timeout 12;
    send_timeout 10;
    
    # Buffer sizes
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 100M;  # Max file upload size
    large_client_header_buffers 2 1k;
    
    # ===========================================================================
    # COMPRESSION CONFIGURATION
    # ===========================================================================
    
    # Enable gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 6;
    gzip_proxied any;
    
    # File types to compress
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        application/atom+xml
        image/svg+xml
        font/truetype
        font/opentype
        application/vnd.ms-fontobject
        application/x-font-ttf;
    
    # Disable gzip for IE6
    gzip_disable "msie6";
    
    # ===========================================================================
    # SECURITY HEADERS
    # ===========================================================================
    
    # Hide Nginx version
    server_tokens off;
    
    # Security headers (applied globally)
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # ===========================================================================
    # RATE LIMITING
    # ===========================================================================
    
    # Define rate limiting zones
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
    limit_req_zone $binary_remote_addr zone=general:10m rate=50r/s;
    limit_req_zone $binary_remote_addr zone=vast:10m rate=100r/s;
    
    # Connection limiting
    limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
    
    # ===========================================================================
    # UPSTREAM CONFIGURATION
    # ===========================================================================
    
    # Django application upstream
    upstream django_app {
        # Health check and load balancing
        least_conn;
        
        # Django web server
        server web:8000 max_fails=3 fail_timeout=30s;
        
        # Add more servers here for load balancing
        # server web2:8000 max_fails=3 fail_timeout=30s;
        
        # Keep alive connections to upstream
        keepalive 32;
    }
    
    # ===========================================================================
    # SERVER BLOCKS
    # ===========================================================================
    
    # Include additional server configurations
    include /etc/nginx/conf.d/*.conf;
}
