# ---- nginx: TLS termination + mTLS + reverse proxy ----
server {
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name _;

    # ---- TLS certificates (mounted at runtime) ----
    ssl_certificate     /etc/nginx/certs/server.crt;
    ssl_certificate_key /etc/nginx/certs/server.key;

    # ---- TLS settings ----
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;

    # ---- Mutual TLS (mTLS) ----
    ssl_client_certificate /etc/nginx/certs/ca.crt;
    ssl_verify_client      on;
    ssl_verify_depth       2;

    # ---- Frontend static files ----
    root /usr/share/nginx/html;
    index index.html;

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

    # ---- Frontend + WebSocket proxy ----
    location / {
        if ($request_uri = "/") {
            return 302 $scheme://$http_host/?proxy=true;
        }

        proxy_http_version 1.1;
        proxy_set_header Upgrade    $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host       $host;
        proxy_read_timeout 86400s;

        if ($is_websocket) {
            proxy_pass http://127.0.0.1:9000;
            break;
        }

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

    # ---- Health check ----
    location /health {
        access_log off;
        default_type text/plain;
        return 200 'OK';
    }

    # ---- Deny hidden files ----
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
}

# ---- Internal health check endpoint ----
server {
    listen 127.0.0.1:8080;
    server_name localhost;

    location /health {
        access_log off;
        default_type text/plain;
        return 200 'OK';
    }
}

# ---- HTTP → HTTPS redirect ----
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}