# ==============================================================================
# Ring2All DMS — Master Hardware Catalog & Provisioning Hub Nginx Configuration
# ==============================================================================

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name _;
    add_header X-Robots-Tag "none" always;

    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_session_tickets off;

    root /var/www/ring2all-dms/web/dist;
    index index.html;

    client_max_body_size 100M;

    # ACME HTTP-01 challenge
    location ^~ /.well-known/acme-challenge/ {
        alias /var/www/ring2all-dms/web/dist/.well-known/acme-challenge/;
        default_type "text/plain";
    }

    # Frontend Single Page App routing
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Static Assets (Logos, Icons, SVGs) - Prevent stale client browser caching
    location /assets/ {
        expires 7d;
        add_header Cache-Control "public, no-transform";
        add_header X-Robots-Tag "none" always;
    }

    # ── Structured JSON 429 Rate-Limit Handler (with Retry-After header for Frontend Warning Modal) ──
    error_page 429 = @rate_limited;
    location @rate_limited {
        default_type application/json;
        add_header Retry-After 5 always;
        add_header Cache-Control "no-store" always;
        return 429 '{"success":false,"error":"RATE_LIMIT_EXCEEDED","code":"RATE_LIMIT_EXCEEDED","retryAfter":5,"message":"Too many requests in a short period. Please wait a few seconds before trying again."}';
    }

    # Backend API proxy
    location /api/ {
        proxy_pass http://127.0.0.1:3000;
        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 120s;
        proxy_connect_timeout 60s;
        proxy_send_timeout 120s;
    }

    # Device Catalog Images
    location /devices/ {
        alias /var/www/ring2all-dms/web/dist/devices/;
        expires 30d;
        add_header Cache-Control "public, no-transform";
        add_header X-Robots-Tag "none" always;
    }

    # Provisioning Uploads / Templates
    location /uploads/ {
        alias /var/www/ring2all-dms/api/uploads/;
        expires 30d;
        add_header Cache-Control "public, no-transform";
        add_header X-Robots-Tag "none" always;
    }
}
