# =============================================================================
# NGINX — Configuracao Global Otimizada para HTTP/3 (QUIC)
# Projeto SUCESU — Laravel 5.5 / PHP 7.2
# Requer NGINX >= 1.25.0 compilado com --with-http_v3_module
# Requer OpenSSL >= 1.1.1
# =============================================================================

user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
pid /var/run/nginx.pid;
pcre_jit on;
error_log /var/log/nginx/error.log warn;

# Carregar modulo HTTP/3 (QUIC)
# Descomente se compilado como module dinamico:
# load_module modules/ngx_http_v3_module.so;

events {
    worker_connections 4096;
    use epoll;
    multi_accept on;
    accept_mutex off;
}

http {
    # ── Caminhos temporarios ────────────────────────────
    client_body_temp_path /tmp/client_temp;
    proxy_temp_path       /tmp/proxy_temp_path;
    fastcgi_temp_path     /tmp/fastcgi_temp;
    uwsgi_temp_path       /tmp/uwsgi_temp;
    scgi_temp_path        /tmp/scgi_temp;

    # ── MIME types ──────────────────────────────────────
    include      /etc/nginx/mime.types;
    default_type application/octet-stream;

    # ── 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" '
                    'proto=$server_protocol';

    access_log /var/log/nginx/access.log main buffer=64k flush=5s;

    # ── Performance — kernel tuning ─────────────────────
    sendfile on;
    sendfile_max_chunk 512k;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 1000;
    types_hash_max_size 2048;

    # ── Open file cache (reduz stat()) ──────────────────
    open_file_cache          max=2000 inactive=20s;
    open_file_cache_valid    30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors   on;

    # ── Conexoes timed-out ──────────────────────────────
    reset_timedout_connection on;
    client_body_timeout       12s;
    client_header_timeout     12s;
    send_timeout              10s;
    lingering_close           off;
    lingering_time            10s;
    lingering_timeout         5s;

    # ── Tamanhos de requisição ──────────────────────────
    client_body_buffer_size 10k;
    client_header_buffer_size 1k;
    client_max_body_size 100M;
    large_client_header_buffers 4 32k;

    # ── Esconder versao do servidor ─────────────────────
    server_tokens off;

    # ── SSL global — compartilhado entre todos os server blocks ──
    ssl_session_cache   shared:SSL:50m;
    ssl_session_timeout 60m;
    ssl_session_tickets on;
    ssl_session_ticket_key /etc/ssl/ticket.key;

    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_ecdh_curve prime256v1:secp384r1;
    ssl_buffer_size 4k;

    # ── OCSP Stapling ───────────────────────────────────
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
    resolver 1.1.1.1 8.8.8.8 valid=300s ipv6=off;
    resolver_timeout 5s;

    # ── HTTP/3 pool de conexoes QUIC ────────────────────
    # Nota: quic_* diretivas disponiveis no NGINX >= 1.25.0
    quic_bpf on;
    quic_gso on;
    quic_retry on;

    # ── FastCGI Cache ───────────────────────────────────
    fastcgi_cache_path /var/cache/nginx/sucesu
                       levels=1:2
                       keys_zone=SUCESU_CACHE:32m
                       inactive=60m
                       max_size=256m
                       use_temp_path=off;

    fastcgi_cache_key       "$scheme$request_method$host$request_uri";
    fastcgi_cache_lock      on;
    fastcgi_cache_lock_age  5s;
    fastcgi_cache_lock_timeout 5s;
    fastcgi_cache_use_stale error timeout updating http_500 http_503;
    fastcgi_cache_background_update  on;
    fastcgi_cache_revalidate         on;

    # ── Rate limiting ───────────────────────────────────
    limit_req_zone $binary_remote_addr zone=login_limit:10m rate=5r/m;
    limit_req_zone $binary_remote_addr zone=api_limit:10m   rate=100r/m;
    limit_req_zone $binary_remote_addr zone=global:10m      rate=500r/s;

    # ── Mapa de bypass do cache por cookie ──────────────
    map $http_cookie $no_cache {
        default 0;
        "~*laravel_session" 1;
        "~*XSRF-TOKEN" 1;
    }

    # ── Compressao Brotli (prioritario) ─────────────────
    # Requer modulo ngx_brotli compilado ou carregado
    brotli on;
    brotli_comp_level 6;
    brotli_min_length 256;
    brotli_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml
        application/xml+rss
        application/x-javascript
        application/wasm
        application/vnd.ms-fontobject
        font/ttf
        image/svg+xml;

    # ── Compressao Gzip (fallback) ──────────────────────
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 1000;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml
        application/xml+rss
        application/x-javascript
        application/wasm
        application/vnd.ms-fontobject
        font/ttf
        image/svg+xml;

    # ── Incluir virtual hosts ───────────────────────────
    include /etc/nginx/conf.d/*.conf;
}
