# Pamsika WhatsApp Bot - Nginx Configuration
# Production-ready reverse proxy with SSL, security headers, and load balancing

worker_processes auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # 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;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none';" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    # Hide Nginx version
    server_tokens off;

    # Logging
    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"';

    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log warn;

    # Performance optimizations
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    client_max_body_size 16M;
    client_body_timeout 60;
    client_header_timeout 60;
    send_timeout 60;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1000;
    gzip_comp_level 6;
    gzip_types
        application/atom+xml
        application/geo+json
        application/javascript
        application/x-javascript
        application/json
        application/ld+json
        application/manifest+json
        application/rdf+xml
        application/rss+xml
        application/xhtml+xml
        application/xml
        font/eot
        font/otf
        font/ttf
        image/svg+xml
        text/css
        text/javascript
        text/plain
        text/xml;

    # Rate limiting
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=health:10m rate=30r/m;
    limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;

    # Upstream for WhatsApp Bot
    upstream pamsika_bot {
        least_conn;
        server pamsika-bot:3003 max_fails=3 fail_timeout=30s;
        # Add more servers for load balancing
        # server pamsika-bot-2:3003 max_fails=3 fail_timeout=30s;
        keepalive 32;
    }

    # HTTP to HTTPS redirect
    server {
        listen 80;
        server_name _;

        # Let's Encrypt challenges
        location /.well-known/acme-challenge/ {
            root /var/www/certbot;
        }

        # Redirect all other traffic to HTTPS
        location / {
            return 301 https://$host$request_uri;
        }
    }

    # Main HTTPS server
    server {
        listen 443 ssl http2;
        server_name localhost;

        # SSL Configuration
        ssl_certificate /etc/nginx/ssl/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/privkey.pem;
        ssl_trusted_certificate /etc/nginx/ssl/chain.pem;

        # SSL Security
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
        ssl_ecdh_curve secp384r1;
        ssl_prefer_server_ciphers off;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
        ssl_session_tickets off;
        ssl_stapling on;
        ssl_stapling_verify on;

        # Health check endpoint (no rate limiting)
        location /health {
            proxy_pass http://pamsika_bot;
            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_connect_timeout 5s;
            proxy_send_timeout 10s;
            proxy_read_timeout 10s;

            # Health check specific settings
            access_log off;
            add_header Cache-Control "no-cache, no-store, must-revalidate";
        }

        # API endpoints with rate limiting
        location ~ ^/(send-message|send-media|payment-update) {
            limit_req zone=api burst=20 nodelay;
            limit_conn conn_limit_per_ip 10;

            proxy_pass http://pamsika_bot;
            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;

            # Timeouts
            proxy_connect_timeout 10s;
            proxy_send_timeout 30s;
            proxy_read_timeout 30s;

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

            # Security headers for API
            add_header X-API-Version "1.0" always;
            add_header X-RateLimit-Limit "100" always;
        }

        # Admin panel endpoints
        location /api/admin {
            # More restrictive rate limiting for admin
            limit_req zone=api burst=10 nodelay;

            proxy_pass http://pamsika_bot;
            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;

            # Admin specific timeouts
            proxy_connect_timeout 10s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }

        # Static admin panel files
        location /admin {
            alias /var/www/admin;
            index index.html;
            try_files $uri $uri/ /index.html;

            # Cache static files
            location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|ttf|eot)$ {
                expires 1y;
                add_header Cache-Control "public, immutable";
                gzip_static on;
            }

            # Security for HTML files
            location ~* \.html$ {
                expires 1h;
                add_header Cache-Control "no-cache";
            }
        }

        # Deny access to sensitive files
        location ~ /\. {
            deny all;
            access_log off;
            log_not_found off;
        }

        location ~ ^/(sessions|users|logs|config)/ {
            deny all;
            access_log off;
            log_not_found off;
        }

        # Block common exploit attempts
        location ~* /(wp-|wordpress|admin|phpmyadmin|mysql|uploads) {
            deny all;
            access_log off;
            log_not_found off;
            return 444;
        }

        # Main proxy location (catch-all)
        location / {
            proxy_pass http://pamsika_bot;
            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;

            # WebSocket support (if needed)
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";

            # Timeouts
            proxy_connect_timeout 10s;
            proxy_send_timeout 30s;
            proxy_read_timeout 30s;
        }

        # Custom error pages
        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;

        location = /404.html {
            root /var/www/error_pages;
            internal;
        }

        location = /50x.html {
            root /var/www/error_pages;
            internal;
        }
    }

    # Development server (HTTP only)
    server {
        listen 8080;
        server_name localhost;

        access_log /var/log/nginx/dev_access.log main;

        location / {
            proxy_pass http://pamsika_bot;
            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;

            # Development specific settings
            proxy_buffering off;
            proxy_cache off;
        }
    }

    # Monitoring endpoints (internal only)
    server {
        listen 127.0.0.1:8081;
        server_name localhost;

        access_log off;

        # Nginx status
        location /nginx_status {
            stub_status on;
            allow 127.0.0.1;
            deny all;
        }

        # Basic metrics
        location /metrics {
            access_log off;
            allow 127.0.0.1;
            deny all;
            proxy_pass http://pamsika_bot/health;
        }
    }
}

# TCP/UDP proxy configuration (if needed for other services)
stream {
    log_format basic '$remote_addr [$time_local] '
                     '$protocol $status $bytes_sent $bytes_received '
                     '$session_time';

    access_log /var/log/nginx/stream_access.log basic;
    error_log /var/log/nginx/stream_error.log;

    # Example Redis proxy
    upstream redis_backend {
        server redis:6379 max_fails=3 fail_timeout=30s;
    }

    server {
        listen 6380;
        proxy_pass redis_backend;
        proxy_timeout 3s;
        proxy_connect_timeout 1s;
        proxy_responses 1;
    }
}
