#!/bin/bash

echo "=========================================="
echo "Phase 2.7 MVP - Comprehensive API Test"
echo "Running on Solaria server"
echo "=========================================="
echo ""

BASE_URL="http://localhost:8001"
MED_ID=""
RANDOM_NUM=0

# Test 1: Health Check
echo "🔍 Test 1: Health Check"
echo "Endpoint: GET /health"
RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" "$BASE_URL/health")
echo "$RESPONSE"
if echo "$RESPONSE" | grep -q "HTTP Status: 200"; then
    echo "✅ PASS"
else
    echo "❌ FAIL"
fi
echo ""

# Test 2: Register New User
echo "🔍 Test 2: Register New User"
echo "Endpoint: POST /api/auth/register"
RANDOM_NUM=$((10000 + RANDOM % 90000))
REGISTER_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "email": "med-test-'$RANDOM_NUM'@example.com",
    "username": "medtest'$RANDOM_NUM'",
    "password": "password123",
    "recovery_phrase": "recovery phrase"
  }' \
  "$BASE_URL/api/auth/register")
echo "$REGISTER_RESPONSE"
TOKEN=$(echo "$REGISTER_RESPONSE" | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
USER_ID=$(echo "$REGISTER_RESPONSE" | grep -o '"user_id":"[^"]*"' | cut -d'"' -f4)
if echo "$REGISTER_RESPONSE" | grep -q "HTTP Status: 201"; then
    echo "✅ PASS"
    echo "User ID: $USER_ID"
else
    echo "❌ FAIL"
fi
echo ""

# Test 3: Login with same credentials
echo "🔍 Test 3: Login"
echo "Endpoint: POST /api/auth/login"
LOGIN_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "email": "med-test-'$RANDOM_NUM'@example.com",
    "password": "password123"
  }' \
  "$BASE_URL/api/auth/login")
echo "$LOGIN_RESPONSE"
TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
if [ -n "$TOKEN" ]; then
    echo "✅ PASS"
    echo "Token obtained: ${TOKEN:0:50}..."
else
    echo "❌ FAIL"
fi
echo ""

# Test 4: Create Medication
echo "🔍 Test 4: Create Medication"
echo "Endpoint: POST /api/medications"
CREATE_MED_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "profile_id": "'$USER_ID'",
    "name": "Aspirin",
    "dosage": "81mg",
    "frequency": "Once daily",
    "instructions": "Take with food",
    "start_date": "2024-01-01",
    "reminders": [{"time": "08:00", "days": ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]}]
  }' \
  "$BASE_URL/api/medications")
echo "$CREATE_MED_RESPONSE"
MED_ID=$(echo "$CREATE_MED_RESPONSE" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
if echo "$CREATE_MED_RESPONSE" | grep -q "HTTP Status: 201\|HTTP Status: 200"; then
    echo "✅ PASS"
    echo "Medication ID: $MED_ID"
else
    echo "❌ FAIL"
fi
echo ""

# Test 5: List Medications
echo "🔍 Test 5: List Medications"
echo "Endpoint: GET /api/medications"
LIST_MEDS_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" \
  -H "Authorization: Bearer $TOKEN" \
  "$BASE_URL/api/medications")
echo "$LIST_MEDS_RESPONSE"
if echo "$LIST_MEDS_RESPONSE" | grep -q "HTTP Status: 200"; then
    echo "✅ PASS"
else
    echo "❌ FAIL"
fi
echo ""

# Test 6: Get Specific Medication
if [ -n "$MED_ID" ]; then
    echo "🔍 Test 6: Get Specific Medication"
    echo "Endpoint: GET /api/medications/$MED_ID"
    GET_MED_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" \
      -H "Authorization: Bearer $TOKEN" \
      "$BASE_URL/api/medications/$MED_ID")
    echo "$GET_MED_RESPONSE"
    if echo "$GET_MED_RESPONSE" | grep -q "HTTP Status: 200"; then
        echo "✅ PASS"
    else
        echo "❌ FAIL"
    fi
    echo ""
fi

# Test 7: Update Medication
if [ -n "$MED_ID" ]; then
    echo "🔍 Test 7: Update Medication"
    echo "Endpoint: POST /api/medications/$MED_ID"
    UPDATE_MED_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X POST \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $TOKEN" \
      -d '{
        "name": "Aspirin Updated",
        "dosage": "100mg"
      }' \
      "$BASE_URL/api/medications/$MED_ID")
    echo "$UPDATE_MED_RESPONSE"
    if echo "$UPDATE_MED_RESPONSE" | grep -q "HTTP Status: 200"; then
        echo "✅ PASS"
    else
        echo "❌ FAIL"
    fi
    echo ""
fi

# Test 8: Log Dose
if [ -n "$MED_ID" ]; then
    echo "🔍 Test 8: Log Dose"
    echo "Endpoint: POST /api/medications/$MED_ID/log"
    LOG_DOSE_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X POST \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $TOKEN" \
      -d '{
        "taken": true,
        "scheduled_time": "2024-01-01T08:00:00Z",
        "notes": "Taken with breakfast"
      }' \
      "$BASE_URL/api/medications/$MED_ID/log")
    echo "$LOG_DOSE_RESPONSE"
    if echo "$LOG_DOSE_RESPONSE" | grep -q "HTTP Status: 201\|HTTP Status: 200"; then
        echo "✅ PASS"
    else
        echo "❌ FAIL"
    fi
    echo ""
fi

# Test 9: Get Adherence
if [ -n "$MED_ID" ]; then
    echo "🔍 Test 9: Get Adherence"
    echo "Endpoint: GET /api/medications/$MED_ID/adherence"
    ADHERENCE_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" \
      -H "Authorization: Bearer $TOKEN" \
      "$BASE_URL/api/medications/$MED_ID/adherence")
    echo "$ADHERENCE_RESPONSE"
    if echo "$ADHERENCE_RESPONSE" | grep -q "HTTP Status: 200"; then
        echo "✅ PASS"
    else
        echo "❌ FAIL"
    fi
    echo ""
fi

# Test 10: Unauthorized Access (No Token)
echo "🔍 Test 10: Unauthorized Access (No Token)"
echo "Endpoint: GET /api/medications"
UNAUTH_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" \
  "$BASE_URL/api/medications")
echo "$UNAUTH_RESPONSE"
if echo "$UNAUTH_RESPONSE" | grep -q "HTTP Status: 401"; then
    echo "✅ PASS - Correctly blocked unauthorized access"
else
    echo "❌ FAIL - Should return 401"
fi
echo ""

# Test 11: Get User Profile
echo "🔍 Test 11: Get User Profile"
echo "Endpoint: GET /api/users/me"
PROFILE_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" \
  -H "Authorization: Bearer $TOKEN" \
  "$BASE_URL/api/users/me")
echo "$PROFILE_RESPONSE"
if echo "$PROFILE_RESPONSE" | grep -q "HTTP Status: 200"; then
    echo "✅ PASS"
else
    echo "❌ FAIL"
fi
echo ""

# Test 12: List Shares
echo "🔍 Test 12: List Shares"
echo "Endpoint: GET /api/shares"
SHARES_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" \
  -H "Authorization: Bearer $TOKEN" \
  "$BASE_URL/api/shares")
echo "$SHARES_RESPONSE"
if echo "$SHARES_RESPONSE" | grep -q "HTTP Status: 200"; then
    echo "✅ PASS"
else
    echo "❌ FAIL"
fi
echo ""

# Test 13: Get Sessions
echo "🔍 Test 13: Get Sessions"
echo "Endpoint: GET /api/sessions"
SESSIONS_RESPONSE=$(curl -s -w "\nHTTP Status: %{http_code}\n" \
  -H "Authorization: Bearer $TOKEN" \
  "$BASE_URL/api/sessions")
echo "$SESSIONS_RESPONSE"
if echo "$SESSIONS_RESPONSE" | grep -q "HTTP Status: 200"; then
    echo "✅ PASS"
else
    echo "❌ FAIL"
fi
echo ""

echo "=========================================="
echo "All Tests Complete!"
echo "=========================================="
