# ==========================================================
# SHBL-CRM Nginx 反向代理配置
# 功能：前端静态资源服务 + 后端 API 转发 + 审计日志
# ==========================================================

# ---- 自定义审计日志格式 ----
# 完整记录：客户端真实 IP、时间、方法、URI、状态码、请求体大小、User-Agent
log_format audit_log '$http_x_forwarded_for - $remote_user [$time_local] '
                     '"$request_method $request_uri $server_protocol" '
                     '$status $body_bytes_sent '
                     '"$http_user_agent" '
                     'req_time=$request_time';

# ---- 后端上游服务 ----
upstream crm_backend {
    server 127.0.0.1:8000;    # FastAPI (uvicorn)
    # 如需多实例负载均衡，在此追加：
    # server 127.0.0.1:8001;
    # server 127.0.0.1:8002;
}

server {
    listen       8080;
    server_name  localhost;
    charset      utf-8;

    # ---- 审计日志输出 ----
    access_log  /var/log/nginx/crm_audit.log  audit_log;
    error_log   /var/log/nginx/crm_error.log  warn;

    # ---- IP 白名单 (取消注释以启用) ----
    # 仅允许内网访问，外网请求直接拒绝
    # allow 192.168.1.0/24;    # 办公室局域网
    # allow 10.0.0.0/8;        # VPN 网段
    # allow 127.0.0.1;         # 本机
    # deny  all;               # 拒绝其他所有 IP

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

    # ---- 前端静态资源 ----
    # Vite 构建输出目录：frontend/dist/
    location / {
        root   /usr/share/nginx/html;
        index  index.html;
        try_files $uri $uri/ /index.html;

        # index.html 不缓存，确保每次获取最新版本
        location = /index.html {
            add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate" always;
            add_header Pragma "no-cache" always;
            expires 0;
        }
    }

    # ---- SSE 长连接专用代理（AI 复盘报告等）----
    location /api/reports/generate {
        proxy_pass         http://crm_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_set_header   Connection        '';

        # SSE 必须: 禁用缓冲，实时推送事件
        proxy_buffering    off;
        proxy_cache        off;
        chunked_transfer_encoding on;

        # LLM 生成可能需要 5-10 分钟
        proxy_connect_timeout 10s;
        proxy_read_timeout    600s;
        proxy_send_timeout    600s;

        client_max_body_size 1m;
    }

    # ---- 后端 API 反向代理 ----
    location /api/ {
        proxy_pass         http://crm_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;

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

        # 超时配置
        proxy_connect_timeout 10s;
        proxy_read_timeout    300s;
        proxy_send_timeout    60s;

        # 请求体大小限制 (报销单附件上传)
        client_max_body_size 50m;
    }

    # ---- 静态资源缓存策略 ----
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
