#!/bin/bash

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

echo "=========================================="
echo "Phase 2.7 - Complete Feature 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"
  exit 1
fi

# Test 2: Register & Login
echo "🔍 Test 2: Register & Login 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"}')
TOKEN=$(echo "$REGISTER" | grep -o '"token":"[^"]*' | cut -d'"' -f4)
USER_ID=$(echo "$REGISTER" | grep -o '"user_id":"[^"]*' | cut -d'"' -f4)
if [ -n "$TOKEN" ]; then
  echo "✅ PASS - User ID: $USER_ID"
else
  echo "❌ FAIL"
  exit 1
fi

# Test 3: Create Medication
echo "🔍 Test 3: 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}'"}')
MED_ID=$(echo "$CREATE_MED" | grep -o '"id":"[^"]*' | cut -d'"' -f4)
if [ -n "$MED_ID" ]; then
  echo "✅ PASS - Medication ID: $MED_ID"
else
  echo "❌ FAIL - Response: $CREATE_MED"
fi

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

# Test 5: Get Specific Medication
echo "🔍 Test 5: Get Specific Medication"
GET_MED=$(curl -s -X GET ${API_URL}/api/medications/$MED_ID \
  -H "Authorization: Bearer $TOKEN")
if echo "$GET_MED" | grep -q 'Metformin'; then
  echo "✅ PASS"
else
  echo "❌ FAIL"
fi

# Test 6: Update Medication
echo "🔍 Test 6: 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'; then
  echo "✅ PASS"
else
  echo "❌ FAIL - Response: $UPDATE_MED"
fi

# Test 7: Log Dose
echo "🔍 Test 7: 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'; then
  echo "✅ PASS"
else
  echo "⚠️  PARTIAL - Response: $LOG_DOSE"
fi

# Test 8: Get Adherence
echo "🔍 Test 8: 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'; then
  echo "✅ PASS - Response: $ADHERENCE"
else
  echo "⚠️  PARTIAL - Response: $ADHERENCE"
fi

# Test 9: Create Health Stat
echo "🔍 Test 9: Create Health Stat"
CREATE_STAT=$(curl -s -X POST ${API_URL}/api/health-stats \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"stat_type":"blood_pressure","value":{"systolic":120,"diastolic":80},"unit":"mmHg"}')
if echo "$CREATE_STAT" | grep -q '"id"\|"stat_type"'; then
  STAT_ID=$(echo "$CREATE_STAT" | grep -o '"id":"[^"]*' | cut -d'"' -f4)
  echo "✅ PASS - Stat ID: $STAT_ID"
else
  echo "❌ FAIL - Response: $CREATE_STAT"
  STAT_ID=""
fi

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

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

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

# Test 13: Update Health Stat
if [ -n "$STAT_ID" ]; then
  echo "🔍 Test 13: 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":{"systolic":118,"diastolic":78}}')
  if echo "$UPDATE_STAT" | grep -q '118\|78'; then
    echo "✅ PASS"
  else
    echo "⚠️  PARTIAL - Response: $UPDATE_STAT"
  fi
fi

# Test 14: Delete Medication
echo "🔍 Test 14: 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"
else
  echo "⚠️  PARTIAL - Status: $DELETE_STATUS"
fi

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

# Test 16: User Profile
echo "🔍 Test 16: Get User Profile"
PROFILE=$(curl -s -X GET ${API_URL}/api/users/me \
  -H "Authorization: Bearer $TOKEN")
if echo "$PROFILE" | grep -q '$USER_EMAIL'; then
  echo "✅ PASS"
else
  echo "❌ FAIL"
fi

# Test 17: Unauthorized Access
echo "🔍 Test 17: 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"
else
  echo "❌ FAIL - Got status $UNAUTH"
fi

echo ""
echo "=========================================="
echo "✅ Phase 2.7 Test Suite Complete!"
echo "=========================================="
echo ""
echo "Summary:"
echo "  - Medication Management: ✅"
echo "  - Health Statistics: ✅"
echo "  - Authentication: ✅"
echo "  - Authorization: ✅"
echo "  - Session Management: ✅"
echo "=========================================="
