# ==============================================================================
# Capeonn Enterprise Production Nginx Configuration
# High-Performance Reverse Proxy, HTTP/2, WebSocket Support & Security Hardening
# ==============================================================================

# Rate limiting zones: 20 req/s per IP for API, burst allowance 40
limit_req_zone $binary_remote_addr zone=capeonn_api_limit:10m rate=20r/s;
limit_req_zone $binary_remote_addr zone=capeonn_auth_limit:10m rate=5r/s;

# Upstream PHP-FPM Socket (adjust version if using php8.3 or higher)
upstream php_fpm {
    server unix:/run/php/php8.2-fpm.sock;
    keepalive 32;
}

# Upstream WebSocket Server (Laravel Reverb / Soketi / Node WS daemon)
upstream websocket_backend {
    server 127.0.0.1:8080;
    keepalive 64;
}

# ------------------------------------------------------------------------------
# HTTP -> HTTPS Redirect (Port 80)
# ------------------------------------------------------------------------------
server {
    listen 80;
    listen [::]:80;
    server_name api.capeonn.com app.capeonn.com;

    # Let's Encrypt ACME challenge directory
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
        try_files $uri =404;
    }

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

# ------------------------------------------------------------------------------
# HTTPS Production Server (Port 443 with HTTP/2)
# ------------------------------------------------------------------------------
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name api.capeonn.com app.capeonn.com;

    root /var/www/capeonn/capeonn-backend/public;
    index index.php index.html;

    charset utf-8;
    client_max_body_size 50M;
    client_body_timeout 60s;
    client_header_timeout 60s;

    # --------------------------------------------------------------------------
    # SSL / TLS Hardening (Mozilla Intermediate Guidelines)
    # --------------------------------------------------------------------------
    ssl_certificate /etc/letsencrypt/live/api.capeonn.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.capeonn.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/api.capeonn.com/chain.pem;

    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:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 1.1.1.1 valid=300s;
    resolver_timeout 5s;

    # --------------------------------------------------------------------------
    # Global Defensive Security Headers
    # --------------------------------------------------------------------------
    add_header X-Frame-Options "DENY" 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; preload" always;
    add_header Permissions-Policy "camera=(), microphone=(), geolocation=*" always;

    # --------------------------------------------------------------------------
    # Compression (Gzip)
    # --------------------------------------------------------------------------
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 256;
    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;

    # --------------------------------------------------------------------------
    # Real-Time WebSocket Reverse Proxy (Laravel Reverb / Soketi)
    # --------------------------------------------------------------------------
    location /app {
        proxy_pass http://websocket_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        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_read_timeout 60s;
        proxy_send_timeout 60s;
        proxy_connect_timeout 60s;
    }

    location /apps {
        proxy_pass http://websocket_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        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_read_timeout 60s;
        proxy_send_timeout 60s;
        proxy_connect_timeout 60s;
    }

    # --------------------------------------------------------------------------
    # Static Assets & Flutter Web Client Caching
    # --------------------------------------------------------------------------
    location ~* \.(?:ico|css|js|gif|jpe?g|png|woff2?|eot|ttf|svg|webp|wasm)$ {
        expires 30d;
        add_header Cache-Control "public, no-transform";
        access_log off;
        try_files $uri =404;
    }

    # Block access to hidden files (.env, .git, .htaccess)
    location ~ /\.(?!well-known).* {
        deny all;
        access_log off;
        log_not_found off;
    }

    # --------------------------------------------------------------------------
    # Sensitive Authentication Rate Limiting
    # --------------------------------------------------------------------------
    location /api/v1/auth/login {
        limit_req zone=capeonn_auth_limit burst=10 nodelay;
        try_files $uri $uri/ /index.php?$query_string;
    }

    # --------------------------------------------------------------------------
    # General API Requests Routing
    # --------------------------------------------------------------------------
    location /api/ {
        limit_req zone=capeonn_api_limit burst=40 nodelay;
        try_files $uri $uri/ /index.php?$query_string;
    }

    # --------------------------------------------------------------------------
    # Primary Application Routing (SPA / Laravel Gateway)
    # --------------------------------------------------------------------------
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # --------------------------------------------------------------------------
    # PHP-FPM FastCGI Handler
    # --------------------------------------------------------------------------
    location ~ \.php$ {
        fastcgi_pass php_fpm;
        fastcgi_index index.php;
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        fastcgi_read_timeout 180s;
        fastcgi_connect_timeout 60s;
        fastcgi_send_timeout 180s;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        fastcgi_param HTTP_PROXY ""; # Mitigate httpoxy vulnerability
        fastcgi_hide_header X-Powered-By;
    }

    # Logging
    access_log /var/log/nginx/capeonn_access.log;
    error_log /var/log/nginx/capeonn_error.log warn;
}
