upstream saf_backend {
    server unix:/var/www/saf-backend/saf_backend.sock fail_timeout=0;
}

server {
    listen 80;
    server_name safstudentactivtiesfamily.com www.safstudentactivtiesfamily.com;
    
    # Redirect HTTP to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name safstudentactivtiesfamily.com www.safstudentactivtiesfamily.com;

    # SSL Configuration - Will be managed by Certbot
    ssl_certificate /etc/letsencrypt/live/safstudentactivtiesfamily.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/safstudentactivtiesfamily.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    # Security Headers
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Frame-Options "DENY" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Content-Security-Policy "default-src 'self' https: data: 'unsafe-inline' 'unsafe-eval';" always;

    # Logging
    access_log /var/log/nginx/saf-access.log;
    error_log /var/log/nginx/saf-error.log;

    # Max upload size
    client_max_body_size 10M;

    # Static files
    location /static/ {
        alias /var/www/saf-backend/staticfiles/;
        expires 30d;
        access_log off;
        add_header Cache-Control "public, max-age=2592000";
    }

    # Media files
    location /media/ {
        alias /var/www/saf-backend/media/;
        expires 30d;
        access_log off;
        add_header Cache-Control "public, max-age=2592000";
    }

    # Proxy to Gunicorn
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://saf_backend;
        
        # WebSocket support
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    # Security: Deny access to .git and other sensitive files
    location ~ /\.(?!well-known).* {
        deny all;
        access_log off;
        log_not_found off;
    }

    # Security: Deny access to sensitive files
    location ~* \.(env|py|pyc|log|txt|md|sh|git|gitignore|gitattributes)$ {
        deny all;
    }
}
