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

BASE_URL="http://127.0.0.1:8000"
EX_COL="exercises"
PL_COL="training_plans"

# Utility: assert status code
function assert_status {
  local code=$1; local expect=$2; local body=$3
  if [[ "$code" -ne "$expect" ]]; then
    echo "? Unerwarteter HTTP-Status: $code, erwartet $expect"
    echo "Response Body: $body"
    exit 1
  fi
}

# Utility: die Antwort per jq extrahieren
function jqf { echo "$1" | jq -r "$2"; }

echo "=== 1) Clean up Collections ==="
curl -s -X DELETE "$BASE_URL/delete-collection?collection=$EX_COL" || true
curl -s -X DELETE "$BASE_URL/delete-collection?collection=$PL_COL" || true
echo "? Alle Collections gelöscht"

echo
echo "=== 2) POST /exercise (Create Exercise) ==="
EX_PAYLOAD=$(jq -n '{
  title: "Kniebeuge",
  summary: "Partnerübung für Stabilität",
  short_description: "Partner drückt von vorne",
  keywords: ["Kraft","Partner"],
  link: "http://wiki/uebung/kniebeuge",
  discipline: "Karate",
  group: "Mittelstufe",
  age_group: "Erwachsene",
  target_group: "Breitensport",
  min_participants: 2,
  duration_minutes: 5,
  capabilities: {"strength":3,"balance":2},
  category: "Grundübung",
  purpose: "Stärkung Beine",
  execution: "Langsam herabsenken",
  notes: "Rücken gerade halten",
  preparation: "Partnerposition",
  method: "Partnerwiderstand",
  equipment: ["Partner"]
}')
R=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/exercise" -H "Content-Type: application/json" -d "$EX_PAYLOAD")
BODY=$(echo "$R" | sed '$d')
CODE=$(echo "$R" | tail -n1)
assert_status $CODE 200 "$BODY"
EX_ID=$(jqf "$BODY" '.id')
echo "? Exercise erstellt mit id=$EX_ID"

echo
echo "=== 3) GET /exercise (List & Filter) ==="
# 3a) ohne Filter
FULL=$(curl -s -X GET "$BASE_URL/exercise")
COUNT=$(echo "$FULL" | jq 'length')
if [[ "$COUNT" -ne 1 ]]; then
  echo "? /exercise returned $COUNT entries, expected 1"
  exit 1
fi
echo "? /exercise list returns $COUNT Eintrag"

# 3b) filter discipline
F=$(curl -s -G "$BASE_URL/exercise" --data-urlencode "discipline=Karate")
if [[ "$(echo "$F" | jq '.[0].id')" != "\"$EX_ID\"" ]]; then
  echo "? discipline filter fehlgeschlagen"
  exit 1
fi
echo "? Filter discipline funktioniert"

# 3c) filter tags
F2=$(curl -s -G "$BASE_URL/exercise" --data-urlencode "tags=Partner")
if [[ "$(echo "$F2" | jq '.[0].id')" != "\"$EX_ID\"" ]]; then
  echo "? tags filter fehlgeschlagen"
  exit 1
fi
echo "? Filter tags funktioniert"

echo
echo "=== 4) POST /plan (Create TrainingPlan) ==="
PLAN_PAYLOAD=$(jq -n --arg exid "$EX_ID" '{
  title: "Bein-Training",
  short_description: "Stabilität und Kraft",
  collection: "training_plans",
  discipline: "Karate",
  group: "Mittelstufe",
  dojo: "Dojo A",
  date: "2025-08-10",
  plan_duration_weeks: 4,
  focus_areas: ["Kraft","Technik"],
  predecessor_plan_id: null,
  age_group: "Erwachsene",
  phases: [
    {
      name: "Aufwärmen",
      duration_minutes: 10,
      method: "Laufen",
      method_notes: "locker",
      exercises: [
        {
          exercise_id: $exid,
          cond_load: {"reps":5},
          coord_load: {"balance":2},
          instructions: "Langsam ausführen"
        }
      ]
    }
  ]
}')
R2=$(curl -s -w "\n%{http_code}" -X POST "$BASE_URL/plan" -H "Content-Type: application/json" -d "$PLAN_PAYLOAD")
BODY2=$(echo "$R2" | sed '$d')
CODE2=$(echo "$R2" | tail -n1)
assert_status $CODE2 200 "$BODY2"
PL_ID=$(jqf "$BODY2" '.id')
echo "? Plan erstellt mit id=$PL_ID"

echo
echo "=== 5) GET /plan (List & Filter) ==="
# 5a) ohne Filter
L=$(curl -s -G "$BASE_URL/plan")
if [[ "$(echo "$L" | jq 'length')" -ne 1 ]]; then
  echo "? /plan returned $(echo $L | jq 'length') entries, expected 1"
  exit 1
fi
echo "? /plan list returns 1 Eintrag"

# 5b) filter discipline
LF=$(curl -s -G "$BASE_URL/plan" --data-urlencode "discipline=Karate")
if [[ "$(echo "$LF" | jq '.[0].id')" != "\"$PL_ID\"" ]]; then
  echo "? discipline filter for /plan failed"
  exit 1
fi
echo "? /plan discipline filter funktioniert"

# 5c) filter group
LG=$(curl -s -G "$BASE_URL/plan" --data-urlencode "group=Mittelstufe")
if [[ "$(echo "$LG" | jq '.[0].id')" != "\"$PL_ID\"" ]]; then
  echo "? group filter for /plan failed"
  exit 1
fi
echo "? /plan group filter funktioniert"

# Cleanup
echo
echo "=== Cleanup Collections ==="
curl -s -X DELETE "$BASE_URL/delete-collection?collection=$EX_COL" || true
curl -s -X DELETE "$BASE_URL/delete-collection?collection=$PL_COL" || true
echo "? Cleanup done"

echo
echo "?? Alle Tests für Exercises & Plans erfolgreich! ??"
