# Configurazione Nginx per VigilanzaTurni
# Salvare in: /etc/nginx/conf.d/vigilanza-turni.conf

upstream vigilanza_backend {
    server 127.0.0.1:5000;
    keepalive 64;
}

# HTTP → HTTPS redirect
server {
    listen 80;
    listen [::]:80;
    server_name vt.alfacom.it;

    # Let's Encrypt challenge
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$server_name$request_uri;
    }
}

# HTTPS Server
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name vt.alfacom.it;

    # SSL Certificate (generato da certbot)
    ssl_certificate /etc/letsencrypt/live/vt.alfacom.it/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/vt.alfacom.it/privkey.pem;

    # SSL Security
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # Security Headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Logs
    access_log /var/log/nginx/vigilanza-turni-access.log;
    error_log /var/log/nginx/vigilanza-turni-error.log;

    # Client max body size (per upload)
    client_max_body_size 10M;

    # Proxy to Node.js backend
    location / {
        proxy_pass http://vigilanza_backend;
        proxy_http_version 1.1;
        
        # Headers
        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;
        
        # Timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
        
        # Cache bypass
        proxy_cache_bypass $http_upgrade;
    }

    # Static assets (dopo build Vite)
    location /assets/ {
        alias /var/www/vigilanza-turni/dist/public/assets/;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1000;
    gzip_types text/plain text/css text/xml text/javascript 
               application/json application/javascript application/xml+rss 
               application/x-font-ttf font/opentype image/svg+xml;
}
