fix missing parenthesis
remove unnecessary complexity
use json_agg instead of array_agg
add some logging