### Run Typesense via Docker ########################################
set -x

export TYPESENSE_API_KEY=xyz
export TYPESENSE_HOST=http://127.0.0.1:8108

podman stop typesense-repro 2>/dev/null
podman rm typesense-repro 2>/dev/null

podman volume create typesense-data
podman volume rm typesense-data

podman run -d -p 8108:8108 --name typesense-repro \
            -v typesense-data:/data:Z \
            docker.io/typesense/typesense:30.1 \
            --data-dir /data \
            --api-key=$TYPESENSE_API_KEY \
            --enable-cors 

# Wait till typesense is ready.
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 -s "$TYPESENSE_HOST/debug" \
       -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" | jq

curl -s "$TYPESENSE_HOST/collections" \
       -X POST \
       -H "Content-Type: application/json" \
       -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
       -d '
          {
             "name": "people",
             "enable_nested_fields": true,
             "fields": [
               {"name": "name", "type": "string" },
               {"name": "locations", "type": "object[]"},
               {"name": "locations.isPrimary", "type": "bool[]", "optional": true },
               {"name": "locations.profileId", "type": "string[]", "reference": "profiles.id", "async_reference": true, "optional": true }
             ]
           }' | jq

curl -s "$TYPESENSE_HOST/collections" \
       -X POST \
       -H "Content-Type: application/json" \
       -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
       -d '
          {
             "name": "profiles",
             "enable_nested_fields": true,
             "fields": [
               {"name": "name", "type": "string" },
               {"name": "tags", "type": "string[]" }
             ]
           }' | jq

curl -s "$TYPESENSE_HOST/collections/profiles/documents/import?action=create" \
        -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
        -H "Content-Type: text/plain" \
        -X POST \
        -d '{"id": "profile-1","name": "Alpha-profile","tags": ["ACTIVE"]}'  | jq

curl -s "$TYPESENSE_HOST/collections/people/documents/import?action=create" \
        -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
        -H "Content-Type: text/plain" \
        -X POST \
        -d '{"id": "1","name": "Alpha","locations": [{"isPrimary": true, "profileId": "profile-1"}]}'  | jq

curl -s --get "$TYPESENSE_HOST/collections/people/documents/search" \
        -H "Content-Type: application/json" \
        -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
        --data-urlencode 'q=*' \
        --data-urlencode 'include_fields=$profiles(tags)' \
        --data-urlencode 'filter_by=locations.{isPrimary:true && $profiles(tags:ACTIVE)}' | jq

podman stop typesense-repro
podman rm typesense-repro
