# =============================================================================
# Configuração do Virtual Host Laravel
# Nginx + PHP-FPM
# =============================================================================

# Mapa de cache: define requisições elegíveis para cache
map $request_uri $cache_key_prefix {
    "/" "homepage";
}

# Mapa de bypass: pula cache quando há cookie de sessão (CSRF seguro)
map $http_cookie $no_cache {
    default 0;
    "~*laravel_session" 1;
    "~*XSRF-TOKEN" 1;
}

# Rate limiting zones
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;

upstream php-fpm {
    server php:9000;
    keepalive 8;
}

server {
    listen 8000;
    listen [::]:8000;
    
    # Em produção, configure o domínio real
    server_name localhost v2.localhost _;
    
    # Document root - pasta public do Laravel
    root /var/www/html/public;
    index index.php index.html;

    # Charset
    charset utf-8;

    # Logs por vhost (opcional, remova se usar log centralizado)
    access_log /var/log/nginx/laravel_access.log;
    error_log /var/log/nginx/laravel_error.log;

    # ==========================================================================
    # Security Headers (Políticas de Segurança)
    # ==========================================================================
    
    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;
    
    # Content Security Policy — permite inline (necessário para scripts SLE gerenciados via banco)
    # NOTA: 'unsafe-inline' em script-src é necessário porque os blocos SLE são armazenados no
    # banco de dados e renderizados como HTML inline — não há como usar nonce nesse fluxo.
    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;

    # ==========================================================================
    # Rotas do Laravel
    # ==========================================================================
    
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Otimização Nível Nginx para o Selo (3.000 RPS)
    location ~ ^/api/v1/selo-operador {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php-fpm;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root/index.php;
        
        # Ignorar Cache-Control/Session do Laravel (bypass seguro via $no_cache)
        fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
        # Cache de 10 minutos (Alta Disponibilidade)
        fastcgi_cache SELO_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;
    }

    # ==========================================================================
    # Entrega Direta de Uploads (Ignora links simbólicos corrompidos no Git)
    # ==========================================================================
    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";
    }
    
    # ==========================================================================
    # PHP-FPM
    # ==========================================================================
    
    location ~ \.php$ {
        try_files $uri =404;
        
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php-fpm;
        fastcgi_index index.php;
        
        # FastCGI params
        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;

        # Esquema da requisição original
        fastcgi_param HTTP_X_FORWARDED_PROTO $scheme;

        # Keepalive com upstream PHP-FPM
        fastcgi_keep_conn on;

        # Segurança: não vazar backtrace do PHP nem versão
        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 SELO_CACHE;
        fastcgi_cache_key "$scheme$request_method$host$request_uri";
        fastcgi_cache_valid 200 60s;
        fastcgi_cache_min_uses 1;
        
        # Bypass para requisições com cookie de sessão
        fastcgi_cache_bypass $no_cache;
        fastcgi_no_cache $no_cache;
        
        add_header X-Cache-Status $upstream_cache_status;
        add_header Vary "Accept-Encoding, Cookie";
    }

    # ==========================================================================
    # Cache de Assets Estáticos Versionados
    # ==========================================================================
    
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|webp|avif)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
        log_not_found off;
    }

    # ==========================================================================
    # Segurança
    # ==========================================================================
    
    # Bloquear acesso a arquivos ocultos (ponto), exceto .well-known para ACME
    location ~ /\.(?!well-known) {
        deny all;
        access_log off;
        log_not_found off;
    }
    
    location ~ /composer\.(json|lock)$ {
        deny all;
    }
    
    location ~ /package(-lock)?\.json$ {
        deny all;
    }
    
    location ~ /phpunit\.xml$ {
        deny all;
    }

    # Bloquear acesso direto a arquivos PHP em pastas sensíveis
    location ~* ^/(storage|vendor|bootstrap)/.+\.php$ {
        deny all;
    }

    # ==========================================================================
    # 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;
    }

    # ==========================================================================
    # Healthcheck endpoints
    # ==========================================================================
    
    # Endpoint para healthcheck do container
    location /health {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }
    

    # ==========================================================================
    # Robots.txt e Favicon
    # ==========================================================================
    
    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;
    }

    # ==========================================================================
    # Suprime 404s de source maps (.map) e well-known do Chrome
    # ==========================================================================

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

    # Allow ACME challenges (Let's Encrypt) through dotfiles protection
    location ~ /\.well-known/acme-challenge/ {
        access_log off;
        log_not_found off;
        try_files $uri =404;
    }
}