# =============================================================================
# Virtual Host SUCESU — HTTP/3 (QUIC) + HTTP/2 + HTTP/1.1
# Laravel 5.5 / PHP 7.2 via FastCGI
# Requer NGINX >= 1.25.0 com --with-http_v3_module e OpenSSL >= 1.1.1
# =============================================================================

server {
    # ── Escuta QUIC (HTTP/3) + HTTPS (HTTP/2/1.1) ──────
    # reuseport essencial para QUIC distribuir conexoes UDP entre workers
    listen 443 quic reuseport;
    listen [::]:443 quic reuseport;
    listen 443 ssl http2 reuseport;
    listen [::]:443 ssl http2 reuseport;

    # HTTP/2 tuning (maximizar multiplexacao sobre TCP)
    http2_max_concurrent_streams 256;
    http2_chunk_size              8k;
    http2_body_preread_size      64k;
    http2_recv_buffer_size      256k;

    # ── Identificacao ───────────────────────────────────
    server_name     suceso.exemplo.com;
    root            /var/www/html/public;
    index           index.php;
    charset         utf-8;

    # ── SSL ─────────────────────────────────────────────
    ssl_certificate     /etc/ssl/certs/suceso.pem;
    ssl_certificate_key /etc/ssl/private/suceso.key;

    # ── Early Data (0-RTT) — apenas para GETs cacheados ─
    # Seguro: o FastCGI cache + bypass por cookie protegem
    # conteudo autenticado contra replay attacks
    ssl_early_data on;

    # ── HTTP/3 Alt-Svc ──────────────────────────────────
    add_header Alt-Svc 'h3=":443"; ma=86400' always;
    add_header X-Alt-Svc-Received $http_alt_svc always;

    # ======================================================================
    # Security Headers
    # ======================================================================

    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy "geolocation=(), camera=(), microphone=(), payment=(), usb=()" always;
    add_header Cross-Origin-Embedder-Policy "require-corp" always;
    add_header Cross-Origin-Opener-Policy "same-origin" always;
    add_header Cross-Origin-Resource-Policy "same-origin" always;

    # Content Security Policy
    # unsafe-inline em script-src necessario para blocos SLE
    # armazenados no banco e renderizados como HTML inline
    add_header Content-Security-Policy "
        default-src 'self';
        script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://www.googletagmanager.com https://www.vlibras.gov.br;
        style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com;
        img-src 'self' data: blob: https://img.youtube.com;
        font-src 'self' data: https://fonts.gstatic.com;
        connect-src 'self' https://www.google-analytics.com https://www.googletagmanager.com https://vitals.vercel-analytics.com;
        frame-src 'self' https://www.youtube.com;
        frame-ancestors 'none';
        base-uri 'self';
        form-action 'self';
        object-src 'none';
    " always;

    # ======================================================================
    # Early Hints (103) — pre-carrega assets criticos antes do HTML
    # ======================================================================

    location = / {
        add_header Link "</css/app.css>; rel=preload; as=style";
        add_header Link "</js/app.js>; rel=preload; as=script";
        try_files $uri $uri/ /index.php?$query_string;
    }

    # ======================================================================
    # Rotas do Laravel (Front Controller)
    # ======================================================================

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # ======================================================================
    # Otimizacao: endpoint selo-operador (alta vazao ~3.000 RPS)
    # ======================================================================

    location ~ ^/api/v1/selo-operador {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root/index.php;

        fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
        fastcgi_cache SUCESU_CACHE;
        fastcgi_cache_valid 200 10m;
        fastcgi_cache_use_stale error timeout updating http_500 http_503;
        fastcgi_cache_lock on;

        add_header X-Cache-Status $upstream_cache_status;
    }

    # ======================================================================
    # PHP-FPM
    # ======================================================================

    location ~ \.php$ {
        try_files $uri =404;

        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;

        include fastcgi_params;
        fastcgi_param HTTP_HOST $http_host;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        fastcgi_param HTTP_X_FORWARDED_PROTO $scheme;

        # Keepalive com upstream PHP-FPM
        fastcgi_keep_conn on;

        # Seguranca
        fastcgi_intercept_errors on;
        fastcgi_hide_header X-Powered-By;

        # Buffers — sem I/O em disco
        fastcgi_buffer_size 32k;
        fastcgi_buffers 8 32k;
        fastcgi_busy_buffers_size 64k;
        fastcgi_temp_file_write_size 64k;
        fastcgi_max_temp_file_size 0;

        # Timeouts
        fastcgi_connect_timeout 10s;
        fastcgi_send_timeout 60s;
        fastcgi_read_timeout 120s;
        fastcgi_socket_keepalive on;

        # ── FastCGI Cache ────────────────────────────────
        fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
        fastcgi_cache SUCESU_CACHE;
        fastcgi_cache_key "$scheme$request_method$host$request_uri";
        fastcgi_cache_valid 200 60s;
        fastcgi_cache_min_uses 1;

        fastcgi_cache_bypass $no_cache;
        fastcgi_no_cache $no_cache;

        add_header X-Cache-Status $upstream_cache_status;
        add_header Vary "Accept-Encoding, Cookie";
    }

    # ======================================================================
    # Entrega Direta de Uploads (storage public)
    # ======================================================================

    location /storage/ {
        alias /var/www/html/storage/app/public/;
        access_log off;
        log_not_found off;
        expires max;
        add_header Cache-Control "public, no-transform, immutable";
    }

    # ======================================================================
    # Cache de Assets Estaticos Versionados
    # ======================================================================

    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|webp|avif)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        add_header Vary "Accept-Encoding";
        access_log off;
        log_not_found off;
    }

    # ======================================================================
    # Rate Limiting
    # ======================================================================

    location ~* /(login|register|password) {
        limit_req zone=login_limit burst=3 nodelay;
        try_files $uri $uri/ /index.php?$query_string;
    }

    location /api/ {
        limit_req zone=api_limit burst=20 nodelay;
        try_files $uri $uri/ /index.php?$query_string;
    }

    # ======================================================================
    # Seguranca — Bloqueio de arquivos sensiveis
    # ======================================================================

    # Arquivos ocultos (ponto), exceto .well-known para ACME
    location ~ /\.(?!well-known) {
        deny all;
        access_log off;
        log_not_found off;
    }

    # Arquivos de configuracao do projeto
    location ~ /composer\.(json|lock)$  { deny all; }
    location ~ /package(-lock)?\.json$  { deny all; }
    location ~ /phpunit\.xml$           { deny all; }
    location ~ /artisan$                { deny all; }

    # PHP em diretorios sensiveis
    location ~* ^/(storage|vendor|bootstrap)/.+\.php$ {
        deny all;
    }

    # ======================================================================
    # Healthcheck
    # ======================================================================

    location = /health {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }

    location = /fpm-ping {
        access_log off;
        fastcgi_pass php:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root/index.php;
        fastcgi_cache_bypass 1;
        fastcgi_no_cache 1;
    }

    # ======================================================================
    # Robots.txt, Favicon, Source Maps
    # ======================================================================

    location = /favicon.ico {
        access_log off;
        log_not_found off;
    }

    location = /robots.txt {
        access_log off;
        log_not_found off;
        try_files $uri /index.php?$query_string;
    }

    location ~ \.map$ {
        access_log off;
        log_not_found off;
        return 404;
    }

    # ======================================================================
    # ACME (Let's Encrypt)
    # ======================================================================

    location ~ /\.well-known/acme-challenge/ {
        access_log off;
        log_not_found off;
        try_files $uri =404;
    }

    # ======================================================================
    # Logs
    # ======================================================================

    access_log /var/log/nginx/sucesu-access.log main buffer=64k flush=5s;
    error_log  /var/log/nginx/sucesu-error.log warn;
}

# =============================================================================
# Redirecionamento HTTP → HTTPS
# =============================================================================

server {
    listen      80;
    listen [::]:80;
    server_name sucesu.exemplo.com;

    # ACME challenges na porta 80 (antes do redirect)
    location ~ /\.well-known/acme-challenge/ {
        access_log off;
        log_not_found off;
        root /var/www/html/public;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}
