#!/bin/bash

# Stop and remove any existing typesense container
docker stop typesense-test 2>/dev/null
docker rm typesense-test 2>/dev/null
rm -rf typesense-data

# Start Typesense
docker run -d \
  -p 8108:8108 \
  -v $(pwd)/typesense-data:/data \
  --name typesense-test \
  typesense/typesense:28.0 \
  --data-dir /data \
  --api-key=xyz \
  --enable-cors

echo "Waiting for Typesense to start..."
sleep 5

# Create collection with Swedish locale and stemming enabled
curl -s -X POST "http://localhost:8108/collections" \
  -H "X-TYPESENSE-API-KEY: xyz" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "test_stem",
    "fields": [
      {"name": "value", "type": "string", "stem": true, "locale": "sv"}
    ]
  }'

# Import test documents
curl -s -X POST "http://localhost:8108/collections/test_stem/documents/import?action=create" \
  -H "X-TYPESENSE-API-KEY: xyz" \
  -H "Content-Type: application/json" \
  -d $'{"id": "1", "value": "Tomat"}
{"id": "2", "value": "Tomater"}
{"id": "3", "value": "Tomatsoppa"}
{"id": "4", "value": "Ost"}
{"id": "5", "value": "Osten"}
{"id": "6", "value": "Ostar"}
{"id": "7", "value": "Ostsås"}'

echo -e "\nWaiting for indexing..."
sleep 2

# Test search for "tomater"
echo -e "\nTesting search with 'tomater':"
curl -s "http://localhost:8108/collections/test_stem/documents/search" \
  -X GET \
  -H "X-TYPESENSE-API-KEY: xyz" \
  -G \
  --data-urlencode "q=tomater" \
  --data-urlencode "query_by=value" | jq '.'


# Clean up
docker stop typesense-test
docker rm typesense-test
rm -rf typesense-data