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

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

    # SEO crawler files — never cache so Googlebot always gets the latest version
    location = /sitemap.xml {
        try_files $uri =404;
        add_header Cache-Control "no-cache, must-revalidate";
        add_header X-Content-Type-Options "nosniff" always;
    }

    location = /robots.txt {
        try_files $uri =404;
        add_header Cache-Control "no-cache, must-revalidate";
    }

    # Health check endpoint
    location = /health {
        proxy_pass http://127.0.0.1:8001/health;
        proxy_set_header Host $host;
    }

    # WebSocket endpoints (ESP32 simulation, etc.)
    # Must come BEFORE the generic /api/ block so nginx matches it first.
    location /api/simulation/ws/ {
        proxy_pass http://127.0.0.1:8001/api/simulation/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 $scheme;
        proxy_read_timeout 86400s;
        proxy_send_timeout 86400s;
    }

    # Proxy /api/* requests to the FastAPI backend.
    # FastAPI Swagger UI is at /api/docs (moved from /docs to avoid
    # conflicting with the frontend /docs/* documentation routes).
    location /api/ {
        proxy_pass http://127.0.0.1:8001/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;
        proxy_read_timeout 300s;
        proxy_connect_timeout 75s;
    }

    # Cache static assets with content-hash filenames (js/css/fonts/images)
    location ~* \.(js|css|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    location ~* \.(png|jpg|jpeg|gif|ico|svg|webp)$ {
        expires 30d;
        add_header Cache-Control "public";
    }

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/json application/xml application/rss+xml;

    # Frontend SPA routing — must be last so specific locations above take precedence
    location / {
        try_files $uri $uri/ /index.html;
    }
}
