worker_processes auto;

events {
  worker_connections 1024;
}

http {
  # Upstreams
  upstream api_backend {
    server localhost:3010;
  }

  upstream ws_backend {
    server localhost:3002;
  }

  upstream web_frontend {
    server localhost:3001;
  }

  # Rate limiting
  limit_req_zone $binary_remote_addr zone=api_limit:10m rate=30r/s;
  limit_req_zone $binary_remote_addr zone=auth_limit:10m rate=5r/s;

  # WebSocket connection upgrade
  map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
  }

  server {
    listen 80;
    server_name localhost;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" 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;

    # Client max body size for file uploads (100MB)
    client_max_body_size 100m;

    # API REST
    location /api/ {
      limit_req zone=api_limit burst=60 nodelay;
      proxy_pass http://api_backend;
      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;
      proxy_read_timeout 300s;
      proxy_send_timeout 300s;
    }

    # Auth endpoints (stricter rate limit)
    location /api/v1/auth/ {
      limit_req zone=auth_limit burst=10 nodelay;
      proxy_pass http://api_backend;
      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;
    }

    # WebSocket
    location /socket.io/ {
      proxy_pass http://ws_backend;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection $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_read_timeout 86400s;
      proxy_send_timeout 86400s;
    }

    # Health check endpoints (no rate limit)
    location ~ ^/(health|api/v1/health)$ {
      proxy_pass http://api_backend;
      proxy_set_header Host $host;
      access_log off;
    }

    # Next.js frontend
    location / {
      proxy_pass http://web_frontend;
      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;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection $connection_upgrade;
      proxy_read_timeout 300s;
    }

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;
  }
}