#!/bin/bash

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

echo "=========================================="
echo "Phase 2.7 - Final API 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 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"}')
if echo "$REGISTER" | grep -q '"token"'; then
  echo "✅ PASS"
  TOKEN=$(echo "$REGISTER" | grep -o '"token":"[^"]*' | cut -d'"' -f4)
  USER_ID=$(echo "$REGISTER" | grep -o '"user_id":"[^"]*' | cut -d'"' -f4)
else
  echo "❌ FAIL"
  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!"}')
if echo "$LOGIN" | grep -q '"token"'; then
  echo "✅ PASS"
  TOKEN=$(echo "$LOGIN" | grep -o '"token":"[^"]*' | cut -d'"' -f4)
else
  echo "❌ FAIL"
fi

# Test 4: Create Medication with profile_id
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":"Lisinopril","dosage":"10mg","frequency":"once_daily","route":"oral","instructions":"Take with breakfast","start_date":"2026-03-01","profile_id":"$USER_ID"}')
if echo "$CREATE_MED" | grep -q '"id"\|"medicationId"'; then
  echo "✅ PASS"
  echo "Response: $CREATE_MED"
else
  echo "❌ FAIL - Response: $CREATE_MED"
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 [ "$?" = "0" ]; then
  echo "✅ PASS"
  echo "Medications: $LIST_MEDS"
else
  echo "❌ FAIL"
fi

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

# Test 7: Unauthorized Access
echo "🔍 Test 7: Unauthorized Access"
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 "✅ Core Tests Complete!"
echo "=========================================="
