# 多租户域名反向代理模板
# 签发: 铸渊 · ICE-GL-ZY001
# 版权: 国作登字-2026-A-00037559
# 用途: 为每个行业租户生成独立的Nginx配置
# 部署位置: ZY-SVR-002 (面孔·新加坡)
#
# 占位符说明（由工作流自动替换）:
#   TENANT_DOMAIN      → 租户域名 (例: guanghutcs.top)
#   TENANT_BACKEND     → 后端地址 (例: 43.139.207.172:3000)
#   TENANT_ID          → 租户标识 (例: webnovel-awen)
#   TENANT_INDUSTRY    → 行业名称 (例: 网文)

# ============================================
# HTTP → HTTPS 自动跳转 (SSL配置后由certbot自动添加)
# ============================================
server {
    listen 80;
    server_name TENANT_DOMAIN;

    # --- 行业接入标识 ---
    # tenant_id: TENANT_ID
    # industry: TENANT_INDUSTRY
    # managed_by: 铸渊 · ICE-GL-ZY001

    # --- Let's Encrypt ACME验证 ---
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    # --- 健康检查端点 (铸渊监控用) ---
    location = /__zy_health {
        access_log off;
        add_header Content-Type application/json;
        return 200 '{"status":"ok","tenant":"TENANT_ID","proxy":"ZY-SVR-002","timestamp":"$time_iso8601"}';
    }

    # --- 主代理 ---
    location / {
        proxy_pass http://TENANT_BACKEND;

        # 标准代理头
        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;

        # WebSocket支持
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # 跨境延迟优化 (新加坡↔广州: ~30ms)
        proxy_connect_timeout 15s;
        proxy_read_timeout 120s;
        proxy_send_timeout 60s;

        # 文件上传限制
        client_max_body_size 50m;

        # 缓冲设置
        proxy_buffering on;
        proxy_buffer_size 4k;
        proxy_buffers 8 16k;

        # 错误页面 (后端不可达时)
        proxy_intercept_errors on;
        error_page 502 503 504 /zy_error_backend.html;
    }

    # --- 后端健康检查 (铸渊用·不暴露给用户) ---
    location = /__zy_backend_health {
        internal;
        proxy_pass http://TENANT_BACKEND/health;
        proxy_connect_timeout 5s;
        proxy_read_timeout 5s;
        access_log off;
    }

    # --- 后端不可达错误页面 ---
    location = /zy_error_backend.html {
        internal;
        add_header Content-Type text/html;
        return 503 '<!DOCTYPE html><html><head><meta charset="utf-8"><title>维护中</title></head><body style="text-align:center;padding:100px;font-family:sans-serif"><h1>🔧 服务维护中</h1><p>后端服务器暂时不可用，请稍后再试。</p><p style="color:#999;font-size:12px">Proxy: ZY-SVR-002 | Tenant: TENANT_ID</p></body></html>';
    }
}
