#!/bin/bash

API_URL="http://localhost:8001"

echo "Testing Health Stats API..."
echo ""

# Register and login
REGISTER=$(curl -s -X POST ${API_URL}/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"health-test@example.com","username":"healthtest","password":"SecurePass123!","first_name":"Test","last_name":"User"}')
TOKEN=$(echo "$REGISTER" | grep -o '"token":"[^"]*' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "❌ Failed to get token"
  exit 1
fi

echo "✅ Got token"

# Test 1: Create health stat with simple numeric value
echo "Test 1: Create health stat (weight)"
CREATE=$(curl -s -X POST ${API_URL}/api/health-stats \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"stat_type":"weight","value":75.5,"unit":"kg"}')
echo "Response: $CREATE"
if echo "$CREATE" | grep -q '"id"'; then
  echo "✅ PASS - Created health stat"
  STAT_ID=$(echo "$CREATE" | grep -o '"id":"[^"]*' | cut -d'"' -f4)
else
  echo "❌ FAIL"
  STAT_ID=""
fi

# Test 2: List health stats
echo ""
echo "Test 2: List health stats"
LIST=$(curl -s -X GET ${API_URL}/api/health-stats \
  -H "Authorization: Bearer $TOKEN")
echo "Response: $LIST"
if echo "$LIST" | grep -q 'weight'; then
  echo "✅ PASS"
else
  echo "❌ FAIL"
fi

# Test 3: Get trends
echo ""
echo "Test 3: Get health trends"
TRENDS=$(curl -s -X GET "${API_URL}/api/health-stats/trends?stat_type=weight&period=7d" \
  -H "Authorization: Bearer $TOKEN")
echo "Response: $TRENDS"
if echo "$TRENDS" | grep -q 'average\|count'; then
  echo "✅ PASS"
else
  echo "❌ FAIL"
fi

# Test 4: Get specific stat
if [ -n "$STAT_ID" ]; then
  echo ""
  echo "Test 4: Get specific health stat"
  GET=$(curl -s -X GET ${API_URL}/api/health-stats/$STAT_ID \
    -H "Authorization: Bearer $TOKEN")
  echo "Response: $GET"
  if echo "$GET" | grep -q 'weight'; then
    echo "✅ PASS"
  else
    echo "❌ FAIL"
  fi
fi

echo ""
echo "=========================================="
echo "✅ Health Stats Tests Complete!"
echo "=========================================="
