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

API="http://localhost:8000"

echo "=== Cleanup collection ==="
curl -s -X DELETE "$API/delete-collection?collection=exercises" | jq -r '.status' || true

echo
echo "=== Create baseline (with external_id) ==="
EXT_ID="mw:pageid:218"
PAYLOAD_1=$(cat <<'JSON'
{
  "title": "Affenklatschen",
  "summary": "Mobilisierung der Schulter",
  "short_description": "Mobilisierung der Schulter",
  "keywords": ["Aufwärmen","Dehnen","Mobilisierung","Schulter"],
  "link": "https://karatetrainer.net/index.php?title=Affenklatschen",
  "discipline": "Allgemein",
  "group": "1",
  "age_group": "Kinder, Schüler, Teenager, Erwachsene",
  "target_group": "Breitensportler",
  "min_participants": 1,
  "duration_minutes": 1,
  "capabilities": {"Flexibilität":1,"Kopplungsfähigkeit":1},
  "category": "Übungen",
  "purpose": "Mobilisierung der Schulter",
  "execution": "Beschreibung A",
  "notes": "Hinweise A",
  "preparation": "Dynamisches Dehnen",
  "method": "",
  "equipment": [],
  "fullurl": "https://karatetrainer.net/index.php?title=Affenklatschen",
  "external_id": "mw:pageid:218",
  "source": "MediaWiki",
  "source_version": "rev-1",
  "fingerprint": "fp-1"
}
JSON
)
curl -s -X POST "$API/exercise" -H "Content-Type: application/json" -d "$PAYLOAD_1" | jq -r '.status // "ok"'

echo
echo "=== Upsert same external_id with changed content (should update, not duplicate) ==="
PAYLOAD_2=$(echo "$PAYLOAD_1" | jq '.summary="NEU: Mobilisierung der Schulter (Update)" | .source_version="rev-2" | .fingerprint="fp-2"')
curl -s -X POST "$API/exercise" -H "Content-Type: application/json" -d "$PAYLOAD_2" | jq -r '.status // "ok"'

echo
echo "=== Check by external_id ==="
curl -s "$API/exercise/by-external-id?external_id=$EXT_ID" | jq

echo
echo "=== Count entries (should be 1) ==="
COUNT=$(curl -s "$API/exercise" | jq '[.[] | select(.title=="Affenklatschen")] | length')
echo "Count=$COUNT"
if [ "$COUNT" != "1" ]; then
  echo "❌ Expected 1, got $COUNT"
  exit 1
fi

echo
echo "=== Verify updated summary ==="
CUR_SUMMARY=$(curl -s "$API/exercise/by-external-id?external_id=$EXT_ID" | jq -r '.payload.summary')
echo "Summary=$CUR_SUMMARY"
if [[ "$CUR_SUMMARY" != "NEU: Mobilisierung der Schulter (Update)" ]]; then
  echo "❌ Update did not apply"
  exit 1
fi

echo
echo "✅ Idempotent upsert OK"
