# /bin/bash
# Debug query_by_weights returning only one result on equal weights
export TYPESENSE_API_KEY=xyz
export TYPESENSE_HOST=http://localhost:8108

docker rm -f debug-long
sudo rm -rf typesense-data

# Wait for Typesense to be ready
docker run -d -p 8108:8108 --name debug-long \
            -v"$(pwd)"/typesense-data:/data \
            typesense/typesense:29.0.rc17 \
            --data-dir /data \
            --api-key=$TYPESENSE_API_KEY \
            --enable-cors
            

until curl -s -o /dev/null -w "%{http_code}" "$TYPESENSE_HOST/health" -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" | grep -q "200"; do
  sleep 2
done


curl "${TYPESENSE_HOST}/collections" \
      -X POST \
      -H "Content-Type: application/json" \
      -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" -d '{
        "name": "books",
        "fields": [
          {"name": "title_one", "type": "string"},
          {"name": "title_two", "type": "string"},
          {"name": "title_three", "type": "string"},
          {"name": "authors", "type": "string[]", "facet": true },
          {"name": "publication_year", "type": "int32", "facet": true }
        ],
        "default_sorting_field": "publication_year"
      }'

curl "${TYPESENSE_HOST}/collections/books/documents" \
      -X POST \
      -H "Content-Type: application/json" \
      -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" -d '{
        "title_one": "The Great Gatsby",
        "title_two": "Teste 1",
        "title_three": "Teste 2",
        "authors": ["F. Scott Fitzgerald"],
        "publication_year": 1925
      }'

curl "${TYPESENSE_HOST}/collections/books/documents" \
      -X POST \
      -H "Content-Type: application/json" \
      -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" -d '{
        "title_one": "Teste 1",
        "title_two": "The Great Gatsby",
        "title_three": "Teste 2",
        "authors": ["F. Scott Fitzgerald"],
        "publication_year": 1925
      }'

curl "${TYPESENSE_HOST}/collections/books/documents" \
      -X POST \
      -H "Content-Type: application/json" \
      -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" -d '{
        "title_one": "Teste 2",
        "title_two": "Teste 1",
        "title_three": "The Great Gatsby",
        "authors": ["F. Scott Fitzgerald"],
        "publication_year": 1925
      }'


result=$(curl -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
"http://localhost:8108/collections/books/documents/search\
?q=The+Great+Gatsby&query_by=title_one,title_two,title_three&query_by_weights=100,100,100&," | jq .)

for i in $(seq 0 $(jq '.hits | length' <<< "$result")); do
  echo "$i: $(jq ".hits[$i].document" <<< "$result")"
done
