#!/bin/bash

API_URL="http://localhost:8001"
USER_EMAIL="ph27-fixed-${RANDOM}@example.com"
USER_NAME="ph27fixed${RANDOM}"

echo "=========================================="
echo "Phase 2.7 - Fixed Test Suite"
echo "=========================================="
echo ""

# Test 1: Health Check
echo "🔍 Test 1: Health Check"
HEALTH=$(curl -s ${API_URL}/health)
if echo "$HEALTH" | grep -q '"status":"ok"'; then
  echo "✅ PASS"
else
  echo "❌ FAIL - Backend not healthy"
  exit 1
fi

# Test 2: Register User
echo "🔍 Test 2: Register User"
REGISTER=$(curl -s -X POST ${API_URL}/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"'${USER_EMAIL}'","username":"'${USER_NAME}'","password":"SecurePass123!","first_name":"Test","last_name":"User"}')

# Extract token and user_id properly
TOKEN=$(echo "$REGISTER" | grep -o '"token":"[^"]*' | cut -d'"' -f4)
USER_ID=$(echo "$REGISTER" | grep -o '"user_id":"[^"]*' | cut -d'"' -f4)

if [ -n "$TOKEN" ] && [ -n "$USER_ID" ]; then
  echo "✅ PASS - User ID: $USER_ID"
else
  echo "❌ FAIL - Token: $TOKEN, User ID: $USER_ID"
  echo "Response: $REGISTER"
  exit 1
fi

# Test 3: Login
echo "🔍 Test 3: Login"
LOGIN=$(curl -s -X POST ${API_URL}/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"'${USER_EMAIL}'","password":"SecurePass123!"}')
LOGIN_TOKEN=$(echo "$LOGIN" | grep -o '"token":"[^"]*' | cut -d'"' -f4)
if [ -n "$LOGIN_TOKEN" ]; then
  echo "✅ PASS"
  TOKEN="$LOGIN_TOKEN"
else
  echo "❌ FAIL"
  exit 1
fi

# Test 4: Create Medication
echo "🔍 Test 4: Create Medication"
CREATE_MED=$(curl -s -X POST ${API_URL}/api/medications \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"name":"Metformin","dosage":"500mg","frequency":"twice_daily","route":"oral","instructions":"Take with meals","start_date":"2026-03-01","profile_id":"'${USER_ID}'"}')

# Try to extract medicationId (UUID format) or _id (ObjectId format)
MED_ID=$(echo "$CREATE_MED" | grep -o '"medicationId":"[^"]*' | cut -d'"' -f4)
if [ -z "$MED_ID" ]; then
  MED_ID=$(echo "$CREATE_MED" | grep -o '"_id":{"$oid":"[^"]*"' | grep -o '[^"]*$' | tr -d '}'))
fi
if [ -z "$MED_ID" ]; then
  MED_ID=$(echo "$CREATE_MED" | grep -o '"id":"[^"]*' | cut -d'"' -f4)
fi

if [ -n "$MED_ID" ]; then
  echo "✅ PASS - Medication ID: $MED_ID"
  echo "Response: $CREATE_MED"
else
  echo "❌ FAIL - Could not extract medication ID"
  echo "Response: $CREATE_MED"
  MED_ID=""
fi

# Test 5: List Medications
echo "🔍 Test 5: List Medications"
LIST_MEDS=$(curl -s -X GET ${API_URL}/api/medications \
  -H "Authorization: Bearer $TOKEN")
if echo "$LIST_MEDS" | grep -q 'Metformin\|medicationId\|medications'; then
  echo "✅ PASS - Found medications"
else
  echo "❌ FAIL"
  echo "Response: $LIST_MEDS"
fi

# Test 6: Get Specific Medication (only if we have an ID)
if [ -n "$MED_ID" ]; then
  echo "🔍 Test 6: Get Specific Medication (ID: $MED_ID)"
  GET_MED=$(curl -s -X GET ${API_URL}/api/medications/$MED_ID \
    -H "Authorization: Bearer $TOKEN")
  if echo "$GET_MED" | grep -q 'Metformin\|medicationId\|medicationData'; then
    echo "✅ PASS"
  else
    echo "❌ FAIL"
    echo "Response: $GET_MED"
  fi
fi

# Test 7: Update Medication
if [ -n "$MED_ID" ]; then
  echo "🔍 Test 7: Update Medication"
  UPDATE_MED=$(curl -s -X POST ${API_URL}/api/medications/$MED_ID \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{"dosage":"1000mg","instructions":"Take with meals, twice daily"}')
  if echo "$UPDATE_MED" | grep -q '1000mg\|success\|medicationId'; then
    echo "✅ PASS - Response: $UPDATE_MED"
  else
    echo "⚠️  PARTIAL - Response: $UPDATE_MED"
  fi
fi

# Test 8: Log Dose
if [ -n "$MED_ID" ]; then
  echo "🔍 Test 8: Log Medication Dose"
  LOG_DOSE=$(curl -s -X POST ${API_URL}/api/medications/$MED_ID/log \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{"taken":true,"notes":"Taken with breakfast"}')
  if echo "$LOG_DOSE" | grep -q '"id"\|success\|taken'; then
    echo "✅ PASS"
  else
    echo "⚠️  PARTIAL - Response: $LOG_DOSE"
  fi
fi

# Test 9: Get Adherence
if [ -n "$MED_ID" ]; then
  echo "🔍 Test 9: Get Medication Adherence"
  ADHERENCE=$(curl -s -X GET ${API_URL}/api/medications/$MED_ID/adherence \
    -H "Authorization: Bearer $TOKEN")
  if echo "$ADHERENCE" | grep -q 'adherence\|total_doses\|percentage'; then
    echo "✅ PASS - $ADHERENCE"
  else
    echo "⚠️  PARTIAL - Response: $ADHERENCE"
  fi
fi

# Test 10: Create Health Stat (simple numeric value)
echo "🔍 Test 10: Create Health Stat (weight)"
CREATE_STAT=$(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"}')

# Extract _id from MongoDB response format
STAT_ID=$(echo "$CREATE_STAT" | grep -o '"_id":{"$oid":"[^"]*"' | sed 's/.*"$oid":"\([^"]*\)".*/\1/')
if [ -z "$STAT_ID" ]; then
  STAT_ID=$(echo "$CREATE_STAT" | grep -o '"id":"[^"]*' | cut -d'"' -f4)
fi

if [ -n "$STAT_ID" ]; then
  echo "✅ PASS - Stat ID: $STAT_ID"
else
  echo "⚠️  PARTIAL - Could not extract ID"
  echo "Response: $CREATE_STAT"
  STAT_ID=""
fi

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

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

# Test 13: Get Specific Health Stat
if [ -n "$STAT_ID" ]; then
  echo "🔍 Test 13: Get Specific Health Stat (ID: $STAT_ID)"
  GET_STAT=$(curl -s -X GET ${API_URL}/api/health-stats/$STAT_ID \
    -H "Authorization: Bearer $TOKEN")
  if echo "$GET_STAT" | grep -q 'weight\|type\|value'; then
    echo "✅ PASS"
  else
    echo "❌ FAIL - Response: $GET_STAT"
  fi
fi

# Test 14: Update Health Stat
if [ -n "$STAT_ID" ]; then
  echo "🔍 Test 14: Update Health Stat"
  UPDATE_STAT=$(curl -s -X PUT ${API_URL}/api/health-stats/$STAT_ID \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d '{"value":76.0}')
  if echo "$UPDATE_STAT" | grep -q '76\|value'; then
    echo "✅ PASS"
  else
    echo "⚠️  PARTIAL - Response: $UPDATE_STAT"
  fi
fi

# Test 15: Delete Medication
if [ -n "$MED_ID" ]; then
  echo "🔍 Test 15: Delete Medication"
  DELETE_MED=$(curl -s -X POST ${API_URL}/api/medications/$MED_ID/delete \
    -H "Authorization: Bearer $TOKEN")
  DELETE_STATUS=$(curl -s -w "%{http_code}" -X GET ${API_URL}/api/medications/$MED_ID \
    -H "Authorization: Bearer $TOKEN" -o /dev/null)
  if [ "$DELETE_STATUS" = "404" ] || [ "$DELETE_STATUS" = "400" ]; then
    echo "✅ PASS - Medication deleted (status: $DELETE_STATUS)"
  else
    echo "⚠️  PARTIAL - Status: $DELETE_STATUS"
  fi
fi

# Test 16: Delete Health Stat
if [ -n "$STAT_ID" ]; then
  echo "🔍 Test 16: Delete Health Stat"
  DELETE_STAT=$(curl -s -X DELETE ${API_URL}/api/health-stats/$STAT_ID \
    -H "Authorization: Bearer $TOKEN")
  if [ -z "$DELETE_STAT" ] || echo "$DELETE_STAT" | grep -q '204\|success'; then
    echo "✅ PASS"
  else
    echo "⚠️  PARTIAL - Response: $DELETE_STAT"
  fi
fi

# Test 17: Get User Profile
echo "🔍 Test 17: Get User Profile"
PROFILE=$(curl -s -X GET ${API_URL}/api/users/me \
  -H "Authorization: Bearer $TOKEN")

# Store the email in a variable for comparison
CURRENT_EMAIL="${USER_EMAIL}"
if echo "$PROFILE" | grep -q "${CURRENT_EMAIL}"; then
  echo "✅ PASS - Email matches: $CURRENT_EMAIL"
elif echo "$PROFILE" | grep -q '"email"'; then
  echo "✅ PASS - Found email field"
else
  echo "❌ FAIL - Email not found"
  echo "Expected: $CURRENT_EMAIL"
  echo "Response: $PROFILE"
fi

# Test 18: Get Sessions
echo "🔍 Test 18: Get User Sessions"
SESSIONS=$(curl -s -X GET ${API_URL}/api/sessions \
  -H "Authorization: Bearer $TOKEN")
if echo "$SESSIONS" | grep -q 'sessions\|Session\|token_version'; then
  echo "✅ PASS"
else
  echo "❌ FAIL - Response: $SESSIONS"
fi

# Test 19: Unauthorized Access
echo "🔍 Test 19: Unauthorized Access Test"
UNAUTH=$(curl -s -w "%{http_code}" -X GET ${API_URL}/api/medications -o /dev/null)
if [ "$UNAUTH" = "401" ]; then
  echo "✅ PASS - Correctly blocked (401)"
else
  echo "❌ FAIL - Got status $UNAUTH (expected 401)"
fi

echo ""
echo "=========================================="
echo "✅ All Tests Complete!"
echo "=========================================="
echo ""
echo "Summary:"
echo "  User ID: $USER_ID"
echo "  Email: $USER_EMAIL"
echo "  Medication ID: $MED_ID"
echo "  Health Stat ID: $STAT_ID"
echo "=========================================="
