# ============================================================
# SBC Admin — Nginx Configuration (SoftSwitch Platform)
# File: /etc/nginx/sites-available/softswitch-sbc
#
# Install on server:
#   cp config/nginx/softswitch-sbc.conf /etc/nginx/sites-available/softswitch-sbc
#   ln -sf /etc/nginx/sites-available/softswitch-sbc /etc/nginx/sites-enabled/softswitch-sbc
#   nginx -t && systemctl reload nginx
#
# Architecture (SoftSwitch convention):
#   HTTP  :80  -> Redirect to HTTPS:443 (+ ACME challenge)
#   HTTPS :443 -> Frontend SPA + API proxy
#
#   Frontend (Vite build):  /var/www/softswitch/sbc/  <- SoftSwitch convention
#   API Backend:            http://127.0.0.1:3003  (sbc-api.service)
#   WebSocket:              http://127.0.0.1:3003  (same process)
#   Credentials:            /etc/softswitch/sbc-credentials
#   API env:                /etc/softswitch/sbc-api.env
#   ODBC:                   /etc/odbc.ini  (shared with SoftSwitch)
#
# SSL (lab):        /etc/nginx/ssl/nginx.crt + nginx.key  (self-signed)
# SSL (production): Replace with Let's Encrypt certificate paths
# ============================================================

upstream sbc_api {
    server 127.0.0.1:3003;
    keepalive 32;
}

# ── HTTP Server -> Redirect to HTTPS (except IP Phone Auto-Provisioning) ─
server {
    listen 80;
    server_name _;
    add_header X-Robots-Tag "none" always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options SAMEORIGIN always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    access_log /var/log/nginx/sbc-admin_access.log;
    error_log  /var/log/nginx/sbc-admin_error.log warn;

    # ACME challenge (Let's Encrypt — no redirect)
    location ^~ /.well-known/acme-challenge/ {
        alias /var/www/softswitch/sbc/.well-known/acme-challenge/;
        default_type "text/plain";
    }

    # ── IP Phone Auto-Provisioning over HTTP ──────────────────
    location ~* "^/provisioning/(?<provpath>.+)$" {
        if ($http_user_agent !~* "(Yealink|Grandstream|Fanvil|Polycom|Cisco|Snom|Htek|Flyingvoice|Panasonic|Gigaset|curl|Wget)") {
            return 403 "Forbidden: Non-telephony device";
        }
        proxy_pass https://pbx_provisioning_backend/api/apps/provisioning/devices/config/$provpath;
        # Default LAN compatibility for self-signed PBX provisioning certificates.
        # Opt-in strict TLS verification once cluster CA cert is installed:
        #   proxy_ssl_verify on;
        #   proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
        #   proxy_ssl_verify_depth 2;
        #   proxy_ssl_server_name on;
        proxy_ssl_verify off;
        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_connect_timeout 5s;
        proxy_read_timeout 15s;
    }

    location ~* "^/(?<devcfg>[0-9a-fA-F]{12}\.(?:cfg|xml|htm|cnf)|cfg[0-9a-fA-F]{12}\.xml|[0-9a-fA-F]{12}-phone\.cfg|y0000000000[0-9]{2}\.cfg)$" {
        if ($http_user_agent !~* "(Yealink|Grandstream|Fanvil|Polycom|Cisco|Snom|Htek|Flyingvoice|Panasonic|Gigaset|curl|Wget)") {
            return 403 "Forbidden: Non-telephony device";
        }
        proxy_pass https://pbx_provisioning_backend/api/apps/provisioning/devices/config/$devcfg;
        # Default LAN compatibility for self-signed PBX provisioning certificates.
        # Opt-in strict TLS verification once cluster CA cert is installed:
        #   proxy_ssl_verify on;
        #   proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
        #   proxy_ssl_verify_depth 2;
        #   proxy_ssl_server_name on;
        proxy_ssl_verify off;
        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_connect_timeout 5s;
        proxy_read_timeout 15s;
    }

    # Everything else -> HTTPS
    location / {
        return 301 https://$host$request_uri;
    }
}

# ── HTTPS Server — SBC Admin Panel & Secure Auto-Provisioning ────────────
server {
    listen 443 ssl;
    http2 on;
    server_name _;
    add_header X-Robots-Tag "none" always;

    # ── SSL ──────────────────────────────────────────────────
    # Lab (self-signed):
    ssl_certificate     /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    # Production (Let's Encrypt):
    # ssl_certificate     /etc/letsencrypt/live/sbc.your-domain.com/fullchain.pem;
    # ssl_certificate_key /etc/letsencrypt/live/sbc.your-domain.com/privkey.pem;

    ssl_protocols             TLSv1.2 TLSv1.3;
    ssl_ciphers               ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache         shared:SSL:10m;
    ssl_session_timeout       1d;
    ssl_session_tickets       off;

    # ── Logs ─────────────────────────────────────────────────
    access_log /var/log/nginx/sbc-admin_ssl_access.log;
    error_log  /var/log/nginx/sbc-admin_ssl_error.log warn;

    # ── 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;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" 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;
        add_header X-Content-Type-Options nosniff always;
        add_header X-Frame-Options SAMEORIGIN always;
        add_header Referrer-Policy strict-origin-when-cross-origin always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" 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."}';
    }

    # ── REST API proxy (/api/) ────────────────────────────────
    location /api/ {
        proxy_pass            http://sbc_api;
        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_set_header      X-SSL-Client-Verify $ssl_client_verify;
        proxy_set_header      X-SSL-Client-Cert $ssl_client_escaped_cert;
        proxy_cache_bypass    $http_upgrade;

        proxy_read_timeout    300s;
        proxy_connect_timeout 60s;
        proxy_send_timeout    300s;

        client_max_body_size  50M;
    }

    # ── WebSocket proxy (/ws/) ────────────────────────────────
    location /ws/ {
        proxy_pass         http://sbc_api;
        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_read_timeout  86400s;
        proxy_send_timeout  86400s;
        proxy_connect_timeout 60s;
    }

    # ── IP Phone Auto-Provisioning Reverse Proxy (HTTPS) ─────────
    location ~* "^/provisioning/(?<provpath>.+)$" {
        if ($http_user_agent !~* "(Yealink|Grandstream|Fanvil|Polycom|Cisco|Snom|Htek|Flyingvoice|Panasonic|Gigaset|curl|Wget)") {
            return 403 "Forbidden: Non-telephony device";
        }
        proxy_pass https://pbx_provisioning_backend/api/apps/provisioning/devices/config/$provpath;
        # Default LAN compatibility for self-signed PBX provisioning certificates.
        # Opt-in strict TLS verification once cluster CA cert is installed:
        #   proxy_ssl_verify on;
        #   proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
        #   proxy_ssl_verify_depth 2;
        #   proxy_ssl_server_name on;
        proxy_ssl_verify off;
        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_connect_timeout 5s;
        proxy_read_timeout 15s;
    }

    location ~* "^/(?<devcfg>[0-9a-fA-F]{12}\.(?:cfg|xml|htm|cnf)|cfg[0-9a-fA-F]{12}\.xml|[0-9a-fA-F]{12}-phone\.cfg|y0000000000[0-9]{2}\.cfg)$" {
        if ($http_user_agent !~* "(Yealink|Grandstream|Fanvil|Polycom|Cisco|Snom|Htek|Flyingvoice|Panasonic|Gigaset|curl|Wget)") {
            return 403 "Forbidden: Non-telephony device";
        }
        proxy_pass https://pbx_provisioning_backend/api/apps/provisioning/devices/config/$devcfg;
        # Default LAN compatibility for self-signed PBX provisioning certificates.
        # Opt-in strict TLS verification once cluster CA cert is installed:
        #   proxy_ssl_verify on;
        #   proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
        #   proxy_ssl_verify_depth 2;
        #   proxy_ssl_server_name on;
        proxy_ssl_verify off;
        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_connect_timeout 5s;
        proxy_read_timeout 15s;
    }

    # ── Health check (without access logs) ────────────────────
    location = /health {
        proxy_pass http://sbc_api/health;
        access_log off;
        proxy_read_timeout 5s;
    }

    # ── PWA Service Worker: MUST NEVER be cached 1y immutable ──────
    location = /sw.js {
        root       /var/www/softswitch/sbc;
        expires    -1;
        add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0" always;
        add_header Service-Worker-Allowed "/" always;
        add_header X-Robots-Tag "none" always;
        add_header X-Content-Type-Options nosniff always;
        add_header X-Frame-Options SAMEORIGIN always;
        add_header Referrer-Policy strict-origin-when-cross-origin always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        try_files  $uri =404;
    }

    # ── Favicons & Branding Templates: no-cache during updates ──────
    location ~* ^/(favicon\.(ico|png)|assets/branding-templates/) {
        root       /var/www/softswitch/sbc;
        expires    -1;
        add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
        add_header X-Robots-Tag "none" always;
        add_header X-Content-Type-Options nosniff always;
        add_header X-Frame-Options SAMEORIGIN always;
        add_header Referrer-Policy strict-origin-when-cross-origin always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    }

    # ── Static assets: maximum cache (Vite generates hashed filenames) ─
    location ~* \.(js|css|woff2?|ttf|eot|svg|png|jpg|ico|webp|map)$ {
        root       /var/www/softswitch/sbc;
        expires    1y;
        add_header Cache-Control "public, immutable";
        add_header X-Robots-Tag "none" always;
        add_header X-Content-Type-Options nosniff always;
        add_header X-Frame-Options SAMEORIGIN always;
        add_header Referrer-Policy strict-origin-when-cross-origin always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        access_log off;
        try_files  $uri =404;
    }

    # ── Setup Wizard HTTP Guard (Zero-Flash Server-Side Gate) ──
    location = /_internal/setup-guard {
        internal;
        proxy_pass http://sbc_api/api/auth/setup-guard;
        proxy_pass_request_body off;
        proxy_set_header Content-Length "";
        proxy_set_header Host $host;
        proxy_set_header Cookie $http_cookie;
        proxy_set_header Authorization $http_authorization;
        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;
    }

    location @setup_redirect_login {
        return 302 /login;
    }

    location ~ ^/setup(-admin)?/?$ {
        auth_request /_internal/setup-guard;
        error_page 401 403 500 502 = @setup_redirect_login;
        root /var/www/softswitch/sbc;
        add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
        add_header X-Robots-Tag "none" always;
        add_header X-Content-Type-Options nosniff always;
        add_header X-Frame-Options SAMEORIGIN always;
        add_header Referrer-Policy strict-origin-when-cross-origin always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        try_files /index.html =404;
    }

    # ── Frontend SPA ──────────────────────────────────────────
    # Production: served from /var/www/softswitch/sbc/
    # Development: fallback to Vite dev server on port 5175
    error_page 418 = @vite_dev_sbc;

    location / {
        root  /var/www/softswitch/sbc;
        index index.html;

        # Disable cache for index.html (SPA) & preserve security headers (Nginx location add_header overrides server level)
        add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
        add_header X-Robots-Tag "none" always;
        add_header X-Content-Type-Options nosniff always;
        add_header X-Frame-Options SAMEORIGIN always;
        add_header Referrer-Policy strict-origin-when-cross-origin always;
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        add_header Pragma "no-cache";
        add_header Expires "0";

        # If index.html is absent -> development mode
        if (!-f /var/www/softswitch/sbc/index.html) {
            return 418;
        }

        try_files $uri $uri/ /index.html;
    }

    # ── Vite dev server fallback (development only) ───────────
    location @vite_dev_sbc {
        proxy_pass         http://127.0.0.1:5175;

        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 86400s;
    }
}
