# 陪练试用版 Nginx配置
# 域名: pl.ireborn.com.cn
# 后端: peilian-backend:8000 (通过外部网络访问 host.docker.internal:8020)
# 前端: peilian-frontend:3000 (通过外部网络访问 host.docker.internal:3020)

upstream pl_backend {
    server host.docker.internal:8020;
}

upstream pl_frontend {
    server host.docker.internal:3020;
}

# HTTP -> HTTPS 重定向
server {
    listen 80;
    server_name pl.ireborn.com.cn;
    
    # Let's Encrypt 验证路径
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
    
    location / {
        return 301 https://$host$request_uri;
    }
}

# HTTPS 服务
server {
    listen 443 ssl http2;
    server_name pl.ireborn.com.cn;

    # SSL证书
    ssl_certificate /etc/letsencrypt/live/pl.ireborn.com.cn/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/pl.ireborn.com.cn/privkey.pem;
    
    # SSL配置
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;

    # 安全头
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # 日志
    access_log /var/log/nginx/pl_access.log;
    error_log /var/log/nginx/pl_error.log;

    # 前端页面
    location / {
        proxy_pass http://pl_frontend;
        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_cache_bypass $http_upgrade;
    }

    # API代理
    location /api/ {
        proxy_pass http://pl_backend;
        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_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    # WebSocket代理（用于HMR）
    location /_hmr {
        proxy_pass http://pl_frontend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }

    # Vite HMR WebSocket
    location /@vite/ {
        proxy_pass http://pl_frontend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
}
