# HTTP Server - Redirect Configuration
server {
    listen 80;
    server_name _;
    add_header X-Robots-Tag "none" always;
    server_tokens off;
    add_header X-Content-Type-Options "nosniff" always;

    # Logs
    access_log /var/log/nginx/softswitch_access.log;
    error_log /var/log/nginx/softswitch_error.log;

    # Exclude ACME challenge from redirect
    location ^~ /.well-known/acme-challenge/ {
        alias /var/www/softswitch/.well-known/acme-challenge/;
        default_type "text/plain";
    }

    # Force HTTPS Redirect
    location / {
        return 301 https://$host$request_uri;
    }
}

# HTTPS Server - Main Proxy Configuration
server {
    listen 443 ssl;
    http2 on;
    server_name _;
    add_header X-Robots-Tag "none" always;
    server_tokens off;
    add_header X-Content-Type-Options "nosniff" always;

    # SSL Configuration (using self-signed generated during install)
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    
    # Modern SSL settings
    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/softswitch_ssl_access.log;
    error_log /var/log/nginx/softswitch_ssl_error.log;

    # ── Backend Billing API Proxy (Port 4001) ──
    # IMPORTANT: Must come BEFORE the generic /api/ block

    # ── Ring2All NCX Direct API & Unbuffered SSE/WS Proxy (Port 3008) ──
    location @ncx_unavailable {
        default_type application/json;
        add_header Cache-Control "no-store" always;
        return 200 '{"ncx_available":false,"customer":null,"journey":[],"tickets":[],"crm_status":{"connected":false,"deep_link_available":false}}';
    }
    location ^~ /api/ncx/ {
        proxy_pass http://127.0.0.1:3008;
        error_page 502 503 504 =200 @ncx_unavailable;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        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_buffering off;
        proxy_cache off;
        proxy_read_timeout 86400s;
        proxy_send_timeout 86400s;
        client_max_body_size 50M;
    }
    location ^~ /api/v1/ncx/ {
        proxy_pass http://127.0.0.1:3008;
        error_page 502 503 504 =200 @ncx_unavailable;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        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_buffering off;
        proxy_cache off;
        proxy_read_timeout 86400s;
        proxy_send_timeout 86400s;
        client_max_body_size 50M;
    }

    # ── 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."}';
    }

    # ── Strict Rate Limiting for Authentication (Brute Force Protection) ──
    location ~ ^/api/(v1/)?auth/login$ {
        limit_req zone=login_limit burst=8 nodelay;

        proxy_pass http://127.0.0.1:3001;
        proxy_http_version 1.1;
        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;
        client_max_body_size 10M;
    }

    # ── MCP OAuth 2.1 Discovery Metadata (.well-known/oauth-protected-resource, oauth-authorization-server) ──
    location ^~ /.well-known/oauth- {
        proxy_pass http://127.0.0.1:3001;
        proxy_http_version 1.1;
        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;
    }

    # ── Backend API Proxy (PBX/Admin on port 3001) ──
    location /api/ {
        limit_req zone=api_limit burst=120 delay=60;
        limit_conn conn_limit 60;

        proxy_pass http://127.0.0.1:3001;
        
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        
        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 300s;
        proxy_connect_timeout 300s;
        proxy_send_timeout 300s;
        
        client_max_body_size 100M;
    }

    # ── Backend WebSockets Proxy (PBX CLI, Realtime) ──
    location /ws/ {
        limit_conn conn_limit 20;

        proxy_pass http://127.0.0.1:3001;
        
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        
        proxy_read_timeout 86400;
        proxy_connect_timeout 300s;
        proxy_send_timeout 86400;
    }

    # ── FreeSWITCH WebRTC Proxy (WSS on port 7443) ──
    location /webrtc {
        limit_req zone=webrtc_limit burst=15 nodelay;
        limit_conn conn_limit 10;

        proxy_pass https://$server_addr:7443;
        
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;

        # Real IP headers forwarded to upstream
        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 86400;
        proxy_connect_timeout 300s;
        proxy_send_timeout 86400;

        # Disable SSL verification for internal FreeSWITCH WSS connection
        proxy_ssl_verify off;
    }

    # ── LiveKit SFU WebRTC Signaling Proxy (WSS on port 7880) ──
    location /livekit/ {
        proxy_pass http://127.0.0.1:7880/;
        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 86400;
        proxy_send_timeout 86400;
    }

    # ── Internal auth subrequest validating LiveKit SFU cluster node targets ──
    location = /_internal/livekit-auth {
        internal;
        proxy_pass http://127.0.0.1:3001/api/internal/livekit-auth;
        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-Original-URI $request_uri;
        proxy_set_header X-LiveKit-Target-Host $lk_host;
        proxy_set_header X-LiveKit-Target-Port $lk_port;
    }

    # ── Multi-Node LiveKit SFU Cluster Signaling Proxy (Authorized Registered Active Nodes Only) ──
    location ~ ^/livekit-node/(127\.0\.0\.1|10\.[0-9]+\.[0-9]+\.[0-9]+|172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]+\.[0-9]+|192\.168\.[0-9]+\.[0-9]+):(78[8-9][0-9])/(.*)$ {
        set $lk_host $1;
        set $lk_port $2;
        set $lk_path $3;
        auth_request /_internal/livekit-auth;
        proxy_pass http://$lk_host:$lk_port/$lk_path$is_args$args;
        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 86400;
        proxy_send_timeout 86400;
    }

    # Provisioning (routed through API server with MAC/domain access controls)
    location /provisioning/ {
        limit_req zone=api_limit burst=60 delay=30;
        proxy_pass http://127.0.0.1:3001;
        proxy_http_version 1.1;
        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;
    }

    # Legacy User Portal audio -> Ring2All Connect audio fallback
    location ^~ /portal/audio/ {
        alias /var/www/softswitch/connect/audio/;
    }

    # Legacy User Portal -> Ring2All Connect Redirect
    location /portal/ {
        return 301 /connect/;
    }
    location = /portal {
        return 301 /connect/;
    }

    # Billing System

    # Phonebook Public Discovery
    location /phonebook/ {
        proxy_pass http://127.0.0.1:3001;
        
        proxy_http_version 1.1;
        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;
    }

    # PWA Service Worker for Switchboard (must revalidate immediately)
    location = /switchboard/sw.js {
        alias /var/www/softswitch/switchboard/sw.js;
        expires -1;
        add_header Cache-Control "no-store, no-cache, must-revalidate, max-age=0" always;
        add_header Service-Worker-Allowed "/switchboard/" always;
        add_header X-Robots-Tag "none" always;
    }

    # Switchboard Application (Monitoring Dashboard)
    location /switchboard/ {
        alias /var/www/softswitch/switchboard/;
        index index.html;

        error_page 418 = @vite_dev_switchboard;
        if (!-f /var/www/softswitch/switchboard/index.html) {
            return 418;
        }

        try_files $uri $uri/ @switchboard_index;
    }
    location @switchboard_index {
        # Serve SPA index for any unmatched subroute (e.g. /switchboard/settings, /switchboard/settings/roles)
        root /var/www/softswitch/switchboard;
        try_files /index.html =404;
    }
    location = /switchboard {
        return 301 /switchboard/;
    }

    # Ring2All Connect (Collaboration, Video & Calls)
    # 1. Static assets with content hash (cache indefinitely)
    location /connect/assets/ {
        alias /var/www/softswitch/connect/assets/;
        expires 1y;
        add_header Cache-Control "public, max-age=31536000, immutable";
        add_header X-Robots-Tag "none" always;
        add_header X-Content-Type-Options "nosniff" always;
        access_log off;
    }

    # 2. Main Connect Application (SPA - Revalidate index.html immediately)
    location /connect/ {
        alias /var/www/softswitch/connect/;
        index index.html;

        # Ensure index.html is revalidated by browsers to prevent stale bundle caches
        add_header Cache-Control "no-cache, no-store, must-revalidate";
        add_header X-Robots-Tag "none" always;
        add_header Pragma "no-cache";
        add_header Expires "0";
        add_header X-Content-Type-Options "nosniff" always;

        error_page 418 = @vite_dev_connect;
        if (!-f /var/www/softswitch/connect/index.html) {
            return 418;
        }

        try_files $uri $uri/ @connect_index;
    }
    location @connect_index {
        # Serve SPA index for any unmatched subroute (e.g. #chat, #meetings, #calls, /connect/ncx-supervisor)
        root /var/www/softswitch/connect;
        add_header Cache-Control "no-cache, no-store, must-revalidate";
        add_header X-Robots-Tag "none" always;
        add_header Pragma "no-cache";
        add_header Expires "0";
        add_header X-Content-Type-Options "nosniff" always;
        try_files /index.html =404;
    }
    location = /connect {
        return 301 /connect/;
    }

    # Ring2All NCX Backend API & Unbuffered SSE/WS Proxy (Port 3008)
    location /ncx-api/ {
        rewrite ^/ncx-api/(.*) /$1 break;
        proxy_pass http://127.0.0.1:3008;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        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_buffering off;
        proxy_cache off;
        proxy_read_timeout 86400s;
        proxy_send_timeout 86400s;
        client_max_body_size 50M;
    }

    # Monitoring API Proxy (Switchboard Backend on port 3500)
    location /monitoring-api/ {
        rewrite ^/monitoring-api/(.*) /$1 break;
        proxy_pass http://127.0.0.1:3500;
        
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        
        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;
    }

    # Monitoring WebSocket (for real-time updates)
    location /monitoring-ws {
        rewrite ^/monitoring-ws$ /ws break;
        rewrite ^/monitoring-ws/(.*)$ /ws/$1 break;
        proxy_pass http://127.0.0.1:3500;
        
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        
        proxy_read_timeout 86400;
    }

    # Block direct static download of provisioning device configurations (contains SIP credentials)
    location ~* ^/uploads/provisioning/.*\.(cfg|xml|cnf|htm|conf|txt)$ {
        deny all;
        return 403;
    }

    # Dynamic branding uploads (revalidate immediately)
    location /uploads/branding/ {
        alias /var/www/softswitch/uploads/branding/;
        expires -1;
        add_header Cache-Control "no-cache, must-revalidate";
        add_header X-Robots-Tag "none" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Content-Security-Policy "default-src 'none'; img-src 'self' data:; media-src 'self'; style-src 'unsafe-inline'; sandbox" always;
    }

    # Static uploads (media files, audio, general assets)
    location /uploads/ {
        alias /var/www/softswitch/uploads/;
        expires 30d;
        add_header Cache-Control "public, immutable";
        add_header X-Robots-Tag "none" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Content-Security-Policy "default-src 'none'; img-src 'self' data:; media-src 'self'; style-src 'unsafe-inline'; sandbox" always;
    }

    error_page 418 = @vite_dev;

    # ── Setup Wizard HTTP Guard (Zero-Flash Server-Side Gate) ──
    location = /_internal/setup-guard {
        internal;
        proxy_pass http://127.0.0.1:3001/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;
        add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
        add_header X-Robots-Tag "none" always;
        try_files /index.html =404;
    }

    # React SPA /apps routes (prevent collision with physical /var/www/softswitch/apps/ backend directory)
    location ^~ /apps {
        root /var/www/softswitch;
        try_files /index.html =404;
    }

    # PWA Service Worker for PBX Admin root (must revalidate immediately)
    location = /sw.js {
        root /var/www/softswitch;
        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;
        try_files $uri =404;
    }

    # Frontend (Production Static / Development Vite Fallback)
    location / {
        root /var/www/softswitch;
        index index.html;

        # Si index.html no existe, significa que el frontend no ha sido compilado
        # asumiendo que estamos en modo desarrollo (npm run dev).
        if (!-f /var/www/softswitch/index.html) {
            return 418;
        }

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

    # Vite Development Proxy Fallbacks
    location @vite_dev {
        proxy_pass http://127.0.0.1:5173;
        
        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;
    }

    location @vite_dev_portal {
        rewrite ^/portal/(.*) /$1 break;
        proxy_pass http://127.0.0.1:3003;
        
        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;
    }

    location @vite_dev_switchboard {
        rewrite ^/switchboard/(.*) /$1 break;
        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;
    }

    location @vite_dev_connect {
        rewrite ^/connect/(.*) /$1 break;
        proxy_pass http://127.0.0.1:5195;
        
        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;
    }

}


