#!/usr/bin/env bash
set -euo pipefail

# Basis-URL (ggf. anpassen)
BASE_URL="${BASE_URL:-http://localhost:8000}"

echo "1??  MediaWiki Health-Check…"
HTTP_CODE=$(curl -s -o /dev/null -w '%{http_code}' "${BASE_URL}/import/wiki/health")
if [[ "$HTTP_CODE" != "200" ]]; then
  echo "? Health-Check fehlgeschlagen (HTTP $HTTP_CODE)"
  exit 1
fi
echo "? Health-Check OK (HTTP 200)"

echo
echo "2??  Exercise-CRU-Test (Stichprobe)…"
# Erst löschen, falls Test-Exercise bereits existiert
curl -s -X DELETE "${BASE_URL}/delete-collection?collection=exercises" > /dev/null || true

# Create
CREATE_RESP=$(curl -s -X POST "${BASE_URL}/exercise" \
  -H 'Content-Type: application/json' \
  -d '{"title":"TestÜbung","summary":"Zusammenfassung","short_description":"Kurz","discipline":"Test","age_group":"Erwachsene","target_group":"Tester","min_participants":1,"duration_minutes":5,"category":"test","purpose":"Test","execution":"Ausführen","notes":"","preparation":"","method":"","equipment":[]}' )

echo "? Create-Response: $CREATE_RESP"

# List
LIST_RESP=$(curl -s "${BASE_URL}/exercise?discipline=Test")
if [[ "$LIST_RESP" != *"TestÜbung"* ]]; then
  echo "? Exercise-List nicht wie erwartet"
  exit 1
fi
echo "? Exercise angelegt und gefunden"

echo
echo "3??  Search-Endpoint-Test…"
# Indexiere manuell einen Chunk
curl -s -X POST "${BASE_URL}/embed" \
  -H 'Content-Type: application/json' \
  -d '{"chunks":[{"text":"Hallo Welt","source":"test","version":"1","title":"T","related_to":"","tags":[],"owner":""}],"collection":"default"}' \
  > /dev/null

SEARCH_RESP=$(curl -s "${BASE_URL}/search?query=Hallo")
if [[ "$SEARCH_RESP" != *"Hallo Welt"* ]]; then
  echo "? Search-Ergebnis nicht korrekt"
  exit 1
fi
echo "? Search liefert erwarteten Treffer"

echo
echo "? Alle Tests erfolgreich durchgelaufen."
