# ═══════════════════════════════════════════════════════════════
#  ARANTES TECNOLOGIA — .htaccess
#  Sprint 3: Segurança, Cache e Performance
# ═══════════════════════════════════════════════════════════════

# ── Forçar HTTPS ─────────────────────────────────────────────
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTPS} off
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

# ── Segurança — Headers HTTP ──────────────────────────────────
<IfModule mod_headers.c>

  # HSTS: força HTTPS por 2 anos, inclui subdomínios e permite preload
  Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"

  # Impede clickjacking — a página não pode ser exibida em iframes
  Header always set X-Frame-Options "DENY"

  # Impede MIME-type sniffing
  Header always set X-Content-Type-Options "nosniff"

  # Referrer controlado — não vaza URL completa para terceiros
  Header always set Referrer-Policy "strict-origin-when-cross-origin"

  # Permissões de APIs do browser — desativa o que não é usado
  Header always set Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=(), interest-cohort=()"

  # XSS Protection (legado, mas ainda útil para browsers antigos)
  Header always set X-XSS-Protection "1; mode=block"

  # Content Security Policy
  # - scripts: apenas arquivos locais (sem CDN externo após Sprint 2)
  # - styles: local + Google Fonts + unsafe-inline (necessário por inline style="" no HTML)
  # - fontes: local + Google Fonts
  # - imagens: local + data URIs + HTTPS genérico (para og:image etc.)
  # - conectar: somente origin própria
  # - frames: nenhum
  # - forms: somente origin própria e WhatsApp
  Header always set Content-Security-Policy "\
    default-src 'self'; \
    script-src 'self'; \
    style-src 'self' https://fonts.googleapis.com 'unsafe-inline'; \
    font-src 'self' https://fonts.gstatic.com; \
    img-src 'self' data: https:; \
    connect-src 'self'; \
    frame-src 'none'; \
    frame-ancestors 'none'; \
    base-uri 'self'; \
    form-action 'self' https://wa.me; \
    upgrade-insecure-requests; \
  "

</IfModule>

# ── Compressão GZIP ───────────────────────────────────────────
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/json
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE text/xml
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE application/ld+json

  # Remove bugs de compressão em browsers antigos
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

# ── Cache-Control por tipo de arquivo ─────────────────────────
<IfModule mod_expires.c>
  ExpiresActive On

  # HTML — sem cache (sempre busca versão mais recente)
  ExpiresByType text/html                            "access plus 0 seconds"

  # CSS e JavaScript — 1 ano (versionado com ?v= nas URLs)
  ExpiresByType text/css                             "access plus 1 year"
  ExpiresByType application/javascript               "access plus 1 year"
  ExpiresByType text/javascript                      "access plus 1 year"

  # Fontes — 1 ano (raramente mudam)
  ExpiresByType font/woff2                           "access plus 1 year"
  ExpiresByType font/woff                            "access plus 1 year"
  ExpiresByType font/ttf                             "access plus 1 year"
  ExpiresByType application/font-woff                "access plus 1 year"
  ExpiresByType application/font-woff2               "access plus 1 year"

  # Imagens — 6 meses
  ExpiresByType image/webp                           "access plus 6 months"
  ExpiresByType image/png                            "access plus 6 months"
  ExpiresByType image/jpg                            "access plus 6 months"
  ExpiresByType image/jpeg                           "access plus 6 months"
  ExpiresByType image/svg+xml                        "access plus 6 months"
  ExpiresByType image/gif                            "access plus 6 months"
  ExpiresByType image/x-icon                         "access plus 6 months"
  ExpiresByType image/vnd.microsoft.icon             "access plus 6 months"

  # Dados estruturados
  ExpiresByType application/ld+json                  "access plus 0 seconds"
  ExpiresByType application/json                     "access plus 0 seconds"
</IfModule>

<IfModule mod_headers.c>
  # Cache imutável para assets com hash/versão na URL
  <FilesMatch "\.(css|js|woff2|woff|ttf)$">
    Header append Cache-Control "public, immutable"
  </FilesMatch>

  # Impede cache para HTML
  <FilesMatch "\.html$">
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires 0
  </FilesMatch>
</IfModule>

# ── ETags — desabilitar para evitar conflito com Cache-Control ─
<IfModule mod_setenvif.c>
  <IfModule mod_headers.c>
    <FilesMatch "\.(ico|jpe?g|png|gif|webp|svg|swf|gz)$">
      Header unset ETag
    </FilesMatch>
  </IfModule>
</IfModule>
FileETag None

# ── Keep-Alive ────────────────────────────────────────────────
<IfModule mod_headers.c>
  Header set Connection keep-alive
</IfModule>

# ── Ocultar versão do servidor ────────────────────────────────
ServerSignature Off
