map $http_x_forwarded_proto $geoflow_forwarded_proto {
    default $http_x_forwarded_proto;
    "" $scheme;
}

map $http_x_forwarded_host $geoflow_forwarded_host {
    default $http_x_forwarded_host;
    "" $host;
}

map $http_x_forwarded_port $geoflow_forwarded_port {
    default $http_x_forwarded_port;
    "" $server_port;
}

map $geoflow_forwarded_proto $geoflow_https {
    default "";
    https on;
}

server {
    listen 80;
    server_name _;

    # Docker 内置 DNS；upstream 使用变量以便容器重建后 IP 变更仍能解析
    resolver 127.0.0.11 valid=10s ipv6=off;

    # 默认 1m 会导致后台多图/大图上传 413；需不小于 PHP post_max_size，并覆盖单次 multipart 总体积
    client_max_body_size 64m;

    root /var/www/html/public;
    index index.php;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log warn;

    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options SAMEORIGIN;
    add_header Referrer-Policy strict-origin-when-cross-origin;

    location = /favicon.ico {
        access_log off;
        log_not_found off;
    }

    location = /robots.txt {
        access_log off;
        log_not_found off;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }

    location ~* \.(?:css|js|jpg|jpeg|gif|png|svg|ico|webp|avif|ttf|otf|woff|woff2)$ {
        expires 7d;
        access_log off;
        add_header Cache-Control "public, max-age=604800, immutable";
        try_files $uri =404;
    }

    # Reverb WebSocket（Pusher 协议）：浏览器走 /reverb/app/{key}，反代到 compose reverb 服务
    # upstream 端口须与 .env.prod 的 REVERB_SERVER_PORT 一致（默认 18080）
    location ~ ^/reverb/(app|apps)/ {
        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 $geoflow_forwarded_proto;
        proxy_set_header X-Forwarded-Host $geoflow_forwarded_host;
        proxy_set_header X-Forwarded-Port $geoflow_forwarded_port;
        proxy_read_timeout 86400s;
        proxy_send_timeout 86400s;
        set $reverb_upstream reverb:18080;
        proxy_pass http://$reverb_upstream;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME /var/www/html/public/index.php;
        fastcgi_param DOCUMENT_ROOT /var/www/html/public;
        fastcgi_param HTTPS $geoflow_https if_not_empty;
        fastcgi_param HTTP_X_FORWARDED_PROTO $geoflow_forwarded_proto;
        fastcgi_param HTTP_X_FORWARDED_HOST $geoflow_forwarded_host;
        fastcgi_param HTTP_X_FORWARDED_PORT $geoflow_forwarded_port;
        set $php_upstream app:9000;
        fastcgi_pass $php_upstream;
        fastcgi_read_timeout 300;
        internal;
    }
}
