# =============================================================================
# MPC Message Router gRPC 代理配置
# =============================================================================
# 域名: mpc-grpc.szaiai.com
# 用途: 为 Service Party App 提供 gRPC 连接到 Message Router
# 后端: Message Router gRPC 服务 (端口 50051)
#
# 部署步骤:
#   1. 放置到: /etc/nginx/sites-available/mpc-grpc.szaiai.com
#   2. 启用: ln -s /etc/nginx/sites-available/mpc-grpc.szaiai.com /etc/nginx/sites-enabled/
#   3. 申请证书: certbot certonly --nginx -d mpc-grpc.szaiai.com
#   4. 重载: nginx -t && systemctl reload nginx
#
# 注意: 此配置完全独立，不影响现有服务
# =============================================================================

# HTTP 重定向到 HTTPS (gRPC 必须使用 HTTPS)
server {
    listen 80;
    listen [::]:80;
    server_name mpc-grpc.szaiai.com;

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

    # 重定向到 HTTPS
    location / {
        return 301 https://$host$request_uri;
    }
}

# HTTPS + gRPC 配置
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name mpc-grpc.szaiai.com;

    # SSL 证书 (Let's Encrypt)
    # 首次部署前需要先申请证书:
    # certbot certonly --nginx -d mpc-grpc.szaiai.com
    ssl_certificate /etc/letsencrypt/live/mpc-grpc.szaiai.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mpc-grpc.szaiai.com/privkey.pem;

    # SSL 配置优化
    ssl_session_timeout 1d;
    ssl_session_cache shared:MPC_SSL:10m;
    ssl_session_tickets off;

    # 现代加密套件
    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:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    # HSTS
    add_header Strict-Transport-Security "max-age=63072000" always;

    # 日志
    access_log /var/log/nginx/mpc-grpc.szaiai.com.access.log;
    error_log /var/log/nginx/mpc-grpc.szaiai.com.error.log;

    # gRPC 代理到 Message Router
    # 后端服务器: 192.168.1.111 (与其他服务相同)
    # Message Router gRPC 端口: 50051
    location / {
        # gRPC 代理
        grpc_pass grpc://192.168.1.111:50051;

        # gRPC 超时设置
        # 会话等待时间较长 (24小时倒计时)，需要较长超时
        grpc_read_timeout 300s;
        grpc_send_timeout 300s;
        grpc_connect_timeout 60s;

        # 错误处理
        error_page 502 = /error502grpc;
    }

    # gRPC 错误处理
    location = /error502grpc {
        internal;
        default_type application/grpc;
        add_header grpc-status 14;
        add_header grpc-message "Message Router unavailable";
        return 204;
    }

    # HTTP 健康检查端点 (用于监控)
    location = /health {
        access_log off;
        return 200 '{"status":"ok","service":"mpc-grpc-proxy"}';
        add_header Content-Type application/json;
    }
}
