# Nginx optimizado para rendimiento local
# worker_processes auto usa todos los CPUs disponibles

upstream api_backend {
    server student-api:5000;
    keepalive 32;
}

server {
    listen 80;
    server_name localhost;
    root /usr/share/nginx/html;
    index index.html;

    # Buffers optimizados
    client_body_buffer_size 16k;
    client_max_body_size 8m;
    proxy_buffer_size 128k;
    proxy_buffers 4 256k;
    proxy_busy_buffers_size 256k;

    # Compresión Gzip
    gzip on;
    gzip_vary on;
    gzip_min_length 256;
    gzip_comp_level 5;
    gzip_proxied any;
    gzip_types
        text/plain
        text/css
        text/javascript
        application/json
        application/javascript
        application/xml
        application/xml+rss
        image/svg+xml;

    # Brotli deshabilitado - requiere nginx-mod-http-brotli
    # brotli on;
    # brotli_comp_level 4;

    # SPA routing
    location / {
        try_files $uri $uri/ /index.html;

        # Cache para HTML (corto)
        add_header Cache-Control "no-cache, must-revalidate";
    }

    # Proxy GraphQL con conexiones persistentes
    location /graphql {
        proxy_pass http://api_backend;
        proxy_http_version 1.1;

        # Keepalive
        proxy_set_header Connection "";

        # WebSocket support
        proxy_set_header Upgrade $http_upgrade;

        # Headers
        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;

        # Timeouts optimizados
        proxy_connect_timeout 10s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    # Health check
    location /health {
        proxy_pass http://api_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }

    # Cache agresivo para assets estáticos
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

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

    # Desactivar logs de assets para reducir I/O
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        access_log off;
    }
}
