include ${NGX_CONF_DIR}/common-includes/server_filters;
include ${NGX_CONF_DIR}/components/${NGX_COMP_DIR_NAME}/ssl_config;
include ${NGX_CONF_DIR}/components/${NGX_COMP_DIR_NAME}/proxy_headers;
include ${NGX_CONF_DIR}/components/${NGX_COMP_DIR_NAME}/config_override;

location /livedata/security {
    if ($request_method = OPTIONS ) {
        set $upstreamservername "LD-${http_origin}";
        rewrite ^ /internaloptions$uri last;
    }
    limit_except GET OPTIONS { deny all; }

    proxy_pass $scheme://$backend;

    proxy_no_cache 1;
    proxy_cache_bypass 1;
}


location ~ ^/livedata/api/snapshotRequest/(agentConfig|agent|agentStats|precisionQueue|skillGroup|agentTaskLog|agentStateLog)$ {

    if ($request_method = OPTIONS ) {
        set $upstreamservername  "LD-${http_origin}";
        rewrite ^ /internaloptions$uri last;
    }

    set_by_lua_file $res ${NGX_LUA_DIR}/cuic_auth_header.lua;
    
    # logic to block unauthorized user, checks if the user requesting the finesse api is present in the system.
    # if user is present, rewrites the url to internal/finesse/api which does the authorization through
    # UserAuth API, else 401 unauthorized is returned.
    rewrite_by_lua_file ${NGX_LUA_DIR}/block_unauthorized_users.lua;
    
    limit_except GET OPTIONS { deny all; }
    
    proxy_pass $scheme://$backend;

    proxy_no_cache 1;
    proxy_cache_bypass 1;
    #proxy_redirect $scheme://$backend_failover $scheme://$backend_failover_proxy;
}

location ~ ^/internaloptions/(.*)$ {
	internal;
	rewrite ^/internaloptions(?<realurl>/.*)$ $realurl break;
  	access_by_lua_file /usr/local/openresty/nginx/lua/checkcorsheaders.lua;
	proxy_pass $scheme://$backend;
	body_filter_by_lua_file  /usr/local/openresty/nginx/lua/cacheoptionsrequests.lua;
}

location / {
	deny all;
    # 421 Misdirected Request
	return 421;
}
