events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Rate limiting для защиты от DDoS
    limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=api_limit_per_ip:10m rate=50r/s;

    # HTTP сервер для локальной разработки (БЕЗ SSL)
    server {
        listen 80;
        server_name ${DOMAIN};

        root /usr/share/nginx/html;
        index index.html;

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

        # Основной location
        location / {
            # Rate limiting для основных страниц
            limit_req zone=req_limit_per_ip burst=20 nodelay;
            
            try_files $uri $uri/ /index.html;
            
            # Базовые заголовки безопасности
            add_header X-Frame-Options "SAMEORIGIN" always;
            add_header X-Content-Type-Options "nosniff" always;
            add_header X-XSS-Protection "1; mode=block" always;
        }

        # Статические файлы
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
            add_header Vary Accept-Encoding;
            
            # Заголовки безопасности для статических файлов
            add_header X-Content-Type-Options "nosniff" always;
        }

        # API
        location /api/ {
            # Rate limiting для API (более строгое)
            limit_req zone=api_limit_per_ip burst=100 nodelay;
            
            proxy_pass http://${BACKEND_CONTAINER}:8000/api/;
            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;
            
            # Заголовки безопасности для API
            add_header X-Frame-Options "SAMEORIGIN" always;
            add_header X-Content-Type-Options "nosniff" always;
            add_header X-XSS-Protection "1; mode=block" always;
        }

        # WebSocket поддержка
        location /ws {
            proxy_pass http://${BACKEND_CONTAINER}:8000/ws;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            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 http;
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Port $server_port;
        }

        # Скрытие информации о сервере
        server_tokens off;
    }
}

