js_shared_dict_zone zone=cache:10m;
js_import njs/main.js;
js_set $cache_dict main.get_cache_dict;

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

upstream frontend {
    server ${FRONTEND_HOST}:${FRONTEND_PORT};
}

upstream backend {
    server ${BACKEND_HOST}:${BACKEND_PORT};
}

server {
    listen ${PORT};
    
    set $proxy_target "";

    location /health {
        access_log off;
        add_header Content-Type text/plain;
        return 200 'healthy';
    }

    location /backend-health {
        proxy_pass http://backend/health;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        access_log off;
    }

    location /frontend-health {
        proxy_pass http://frontend;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        access_log off;
    }
    
    location /api {
        proxy_pass http://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;
    }
    
    # Game WebSocket routing
    location ~/api/room/([^/]+)/socket {
        set $room_id $1;
        js_content main.routeWebSocket;
    }

    # WebSocket proxy location
    location @websocket_proxy {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $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;
        
        # Timeouts
        proxy_connect_timeout 7m;
        proxy_send_timeout 7m;
        proxy_read_timeout 7m;
        proxy_buffering off;
        
        proxy_pass $proxy_target;
    }
    
    location / {
        proxy_pass http://frontend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}