# =============================================================================
# Production Nginx Configuration for IdentityPlanKit
# =============================================================================
# Features:
# - SSL/TLS termination with modern security settings
# - Load balancing across multiple app instances
# - Rate limiting and request size limits
# - Security headers
# - Gzip compression
# - Health check endpoints bypass
# - WebSocket support (if needed)
# =============================================================================

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

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

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

    # Logging format with request timing
    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;

    # Performance
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    # Security - hide nginx version
    server_tokens off;

    # -------------------------------------------------------------------------
    # Gzip Compression
    # -------------------------------------------------------------------------
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml application/json application/javascript
               application/xml application/xml+rss text/javascript application/x-javascript;

    # -------------------------------------------------------------------------
    # Rate Limiting
    # -------------------------------------------------------------------------
    # Limit requests per IP
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;
    limit_req_zone $binary_remote_addr zone=auth_limit:10m rate=10r/s;

    # Limit connections per IP
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

    # -------------------------------------------------------------------------
    # Upstream Application Servers
    # -------------------------------------------------------------------------
    upstream app_servers {
        # Load balancing method (least_conn is good for varying request times)
        least_conn;

        # App servers (Docker Compose service discovery)
        server app:8000 max_fails=3 fail_timeout=30s;

        # For multiple instances:
        # server app_1:8000 max_fails=3 fail_timeout=30s;
        # server app_2:8000 max_fails=3 fail_timeout=30s;
        # server app_3:8000 max_fails=3 fail_timeout=30s;

        # Keepalive connections to upstream
        keepalive 32;
    }

    # -------------------------------------------------------------------------
    # HTTP Server (Redirect to HTTPS)
    # -------------------------------------------------------------------------
    server {
        listen 80;
        listen [::]:80;
        server_name api.yourdomain.com;

        # Allow health checks over HTTP
        location /health {
            proxy_pass http://app_servers;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
        }

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

    # -------------------------------------------------------------------------
    # HTTPS Server
    # -------------------------------------------------------------------------
    server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name api.yourdomain.com;

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

        # Modern SSL configuration
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
        ssl_prefer_server_ciphers off;

        # SSL session caching
        ssl_session_timeout 1d;
        ssl_session_cache shared:SSL:50m;
        ssl_session_tickets off;

        # OCSP Stapling
        ssl_stapling on;
        ssl_stapling_verify on;
        resolver 8.8.8.8 8.8.4.4 valid=300s;
        resolver_timeout 5s;

        # ---------------------------------------------------------------------
        # 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 Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

        # Content Security Policy (adjust based on your needs)
        # add_header Content-Security-Policy "default-src 'self';" always;

        # ---------------------------------------------------------------------
        # Request Limits
        # ---------------------------------------------------------------------
        client_max_body_size 10M;
        client_body_timeout 60s;
        client_header_timeout 60s;

        # Connection limits
        limit_conn conn_limit 20;

        # ---------------------------------------------------------------------
        # Health Check Endpoints (no rate limiting)
        # ---------------------------------------------------------------------
        location /health {
            proxy_pass http://app_servers;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;

            # Disable access logging for health checks
            access_log off;
        }

        location /health/live {
            proxy_pass http://app_servers;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            access_log off;
        }

        location /health/ready {
            proxy_pass http://app_servers;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            access_log off;
        }

        # ---------------------------------------------------------------------
        # Metrics Endpoint (restrict access)
        # ---------------------------------------------------------------------
        location /metrics {
            # Restrict to internal networks or specific IPs
            # allow 10.0.0.0/8;
            # allow 172.16.0.0/12;
            # allow 192.168.0.0/16;
            # deny all;

            proxy_pass http://app_servers;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            access_log off;
        }

        # ---------------------------------------------------------------------
        # Auth Endpoints (stricter rate limiting)
        # ---------------------------------------------------------------------
        location /auth {
            limit_req zone=auth_limit burst=20 nodelay;

            proxy_pass http://app_servers;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            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-Request-ID $request_id;

            # Timeouts
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }

        # ---------------------------------------------------------------------
        # API Endpoints
        # ---------------------------------------------------------------------
        location /api {
            limit_req zone=api_limit burst=50 nodelay;

            proxy_pass http://app_servers;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            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-Request-ID $request_id;

            # Timeouts
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }

        # ---------------------------------------------------------------------
        # Admin Endpoints (strictest rate limiting)
        # ---------------------------------------------------------------------
        location /admin {
            limit_req zone=auth_limit burst=10 nodelay;

            proxy_pass http://app_servers;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            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-Request-ID $request_id;

            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }

        # ---------------------------------------------------------------------
        # Default Location (all other routes)
        # ---------------------------------------------------------------------
        location / {
            limit_req zone=api_limit burst=50 nodelay;

            proxy_pass http://app_servers;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            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-Request-ID $request_id;

            # Timeouts
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;

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

        # ---------------------------------------------------------------------
        # Error Pages
        # ---------------------------------------------------------------------
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/share/nginx/html;
            internal;
        }
    }
}
