# /etc/nginx/sites-available/ranchlands
# Symlink to enable: sudo ln -s /etc/nginx/sites-available/ranchlands /etc/nginx/sites-enabled/

server {
    listen 80;
    server_name yourdomain.com;               # ← change this

    # Redirect HTTP to HTTPS (remove this block if you're not using SSL yet)
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;                     # ← remove ssl/http2 if no SSL yet,
    server_name yourdomain.com;               #   and change listen to 80

    # SSL — managed by Certbot (run: sudo certbot --nginx -d yourdomain.com)
    # ssl_certificate     /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    # ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    # include             /etc/letsencrypt/options-ssl-nginx.conf;
    # ssl_dhparam         /etc/letsencrypt/ssl-dhparams.pem;

    # ── Static React frontend ─────────────────────────────────────────────────
    root /var/www/ranchlands;                 # ← where you'll put the built client
    index index.html;

    # SPA routing — send all non-file requests to index.html
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Cache static assets aggressively
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        try_files $uri =404;
    }

    # ── Node.js API (port 8584) ───────────────────────────────────────────────
    location /api/ {
        proxy_pass         http://127.0.0.1:8584;
        proxy_http_version 1.1;
        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
        proxy_connect_timeout 10s;
        proxy_send_timeout    30s;
        proxy_read_timeout    30s;
    }

    # ── WebSocket (Socket.IO) ─────────────────────────────────────────────────
    location /socket.io/ {
        proxy_pass         http://127.0.0.1:8584;
        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;

        # WebSockets need longer timeouts
        proxy_connect_timeout 7d;
        proxy_send_timeout    7d;
        proxy_read_timeout    7d;
    }

    # ── Security headers ──────────────────────────────────────────────────────
    add_header X-Frame-Options        "SAMEORIGIN"   always;
    add_header X-Content-Type-Options "nosniff"      always;
    add_header Referrer-Policy        "strict-origin" always;

    # ── Logging ───────────────────────────────────────────────────────────────
    access_log /var/log/nginx/ranchlands_access.log;
    error_log  /var/log/nginx/ranchlands_error.log;
}
