# 宿主机 Nginx：443 终止 TLS
# - /api/、/ai/、/gateway/ → 本机 gateway（127.0.0.1:8180），避免经 web 容器 DNS 偶发 502
# - 静态页与其它路径 → web（127.0.0.1:5173）
#
# 占位符（由 scripts/lib-aijz-deploy.sh 替换）：
#   __DOMAIN__         站点域名
#   __WEB_PORT__       宿主机 web 映射端口（默认 5173）
#   __GATEWAY_PORT__   宿主机 gateway 映射端口（默认 8180）
#   __VERIFY_ROOT__    域名验证文件目录（项目 verify-root/）

server {
    listen 80;
    listen [::]:80;
    server_name __DOMAIN__;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name __DOMAIN__;
    client_max_body_size 128m;

    ssl_certificate     /etc/ssl/aijianzhan/__DOMAIN__/fullchain.pem;
    ssl_certificate_key /etc/ssl/aijianzhan/__DOMAIN__/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_protocols TLSv1.2 TLSv1.3;

    location ~ ^/[A-Za-z0-9._-]+\.(txt|html|xml)$ {
        root __VERIFY_ROOT__;
        try_files $uri =404;
        default_type text/plain;
        add_header Cache-Control "no-store";
    }

    location /api/ {
        proxy_pass http://127.0.0.1:__GATEWAY_PORT__;
        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;
        proxy_set_header Authorization $http_authorization;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
        client_max_body_size 128m;
    }

    location /ai/ {
        proxy_pass http://127.0.0.1:__GATEWAY_PORT__;
        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;
        proxy_set_header Authorization $http_authorization;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
        client_max_body_size 128m;
    }

    location /gateway/ {
        proxy_pass http://127.0.0.1:__GATEWAY_PORT__;
        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;
        proxy_read_timeout 60s;
    }

    location / {
        proxy_pass http://127.0.0.1:__WEB_PORT__;
        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;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }
}
