# ============================================================
# SBC Admin — Nginx Configuration (SoftSwitch Platform)
# File: /etc/nginx/sites-available/softswitch-sbc
#
# Instalar en el servidor:
#   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 a 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  (mismo proceso)
#   Credentials:            /etc/softswitch/sbc-credentials
#   API env:                /etc/softswitch/sbc-api.env
#   ODBC:                   /etc/odbc.ini  (shared con SoftSwitch)
#
# SSL (lab):        /etc/nginx/ssl/nginx.crt + nginx.key  (auto-firmado)
# SSL (producción): Reemplazar por Let's Encrypt paths
# ============================================================

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

# ── HTTP Server → Redirect a HTTPS ───────────────────────────
server {
    listen 80;
    server_name _;

    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";
    }

    # Todo lo demás → HTTPS
    location / {
        return 301 https://$host$request_uri;
    }
}

# ── HTTPS Server — SBC Admin Panel ───────────────────────────
server {
    listen 443 ssl;
    http2 on;
    server_name _;

    # ── SSL ──────────────────────────────────────────────────
    # Lab (auto-firmado):
    ssl_certificate     /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    # Producción (Let's Encrypt):
    # ssl_certificate     /etc/letsencrypt/live/sbc.tu-dominio.com/fullchain.pem;
    # ssl_certificate_key /etc/letsencrypt/live/sbc.tu-dominio.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;

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

    # ── 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_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;
    }

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

    # ── Static assets: cache máximo (Vite genera hashes) ─────
    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";
        access_log off;
        try_files  $uri =404;
    }

    # ── Frontend SPA ──────────────────────────────────────────
    # Producción: sirve desde /var/www/softswitch/sbc/
    # Desarrollo: fallback al servidor Vite en puerto 5175
    error_page 418 = @vite_dev_sbc;

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

        # No cache para index.html (SPA)
        add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
        add_header Pragma "no-cache";
        add_header Expires "0";

        # Si index.html no existe → estamos en modo dev
        if (!-f /var/www/softswitch/sbc/index.html) {
            return 418;
        }

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

    # ── Vite dev server fallback (solo desarrollo) ────────────
    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;
    }
}
