# ==========================================
# Nginx Configuration for PM2 Reverse Proxy
# Target Path on VPS: /etc/nginx/sites-available/volubit-be-laravel
# ==========================================

server {
    listen 80;
    listen [::]:80;
    server_name your-domain.com www.your-domain.com;

    # Root directory for static asset checks
    root /var/www/volubit-be-laravel/public;

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

    # File upload limit (for media/file uploads)
    client_max_body_size 64M;

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

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

    # Serve static assets directly via Nginx ONLY if file exists on disk
    location ~* \.(jpg|jpeg|gif|png|css|js|ico|webp|svg|woff|woff2|ttf|eot)$ {
        expires 365d;
        add_header Cache-Control "public, no-transform";
        try_files $uri @proxy;
        access_log off;
    }

    # Storage Link access (for user uploads)
    location /storage/ {
        alias /var/www/volubit-be-laravel/storage/app/public/;
        access_log off;
        expires 30d;
    }

    # Deny access to hidden files (.env, .git, etc.)
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    # All web requests proxy directly to PM2 (port 8000)
    location / {
        proxy_pass http://127.0.0.1:8000;
        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_cache_bypass $http_upgrade;
        proxy_read_timeout 300;
        proxy_connect_timeout 300;
    }

    # Fallback named proxy block for static assets
    location @proxy {
        proxy_pass http://127.0.0.1:8000;
        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_cache_bypass $http_upgrade;
    }
}
