#!/bin/bash
BASE_URL="http://localhost:8001"

echo "=== Phase 2.7 Medication API Tests ==="
echo ""

# Test 1: Register
echo "Test 1: Register User"
RND=$((10000 + RANDOM % 90000))
REGISTER=$(curl -s -X POST -H "Content-Type: application/json" \
  -d '{"email":"test'$RND'@example.com","username":"test'$RND'","password":"password123"}' \
  "$BASE_URL/api/auth/register")
echo "$REGISTER"
TOKEN=$(echo "$REGISTER" | grep -o '"token":"[^"]*"' | cut -d'"' -f4 | head -1)
USER_ID=$(echo "$REGISTER" | grep -o '"user_id":"[^"]*"' | cut -d'"' -f4 | head -1)
echo "Token: ${TOKEN:0:50}..."
echo "User ID: $USER_ID"
echo ""

# Test 2: Create Medication
echo "Test 2: Create Medication"
CREATE=$(curl -s -w "\nStatus: %{http_code}" -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"profile_id":"'$USER_ID'","name":"Aspirin","dosage":"81mg","frequency":"daily"}' \
  "$BASE_URL/api/medications")
echo "$CREATE"
MED_ID=$(echo "$CREATE" | grep -o '"id":"[^"]*"' | cut -d'"' -f4 | head -1)
echo "Med ID: $MED_ID"
echo ""

# Test 3: List Medications
echo "Test 3: List Medications"
curl -s -w "\nStatus: %{http_code}\n" \
  -H "Authorization: Bearer $TOKEN" \
  "$BASE_URL/api/medications"
echo ""

# Test 4: Get Specific Medication
if [ -n "$MED_ID" ]; then
    echo "Test 4: Get Medication $MED_ID"
    curl -s -w "\nStatus: %{http_code}\n" \
      -H "Authorization: Bearer $TOKEN" \
      "$BASE_URL/api/medications/$MED_ID"
    echo ""
fi

# Test 5: Update Medication
if [ -n "$MED_ID" ]; then
    echo "Test 5: Update Medication"
    curl -s -w "\nStatus: %{http_code}\n" -X POST \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $TOKEN" \
      -d '{"name":"Aspirin Updated"}' \
      "$BASE_URL/api/medications/$MED_ID"
    echo ""
fi

# Test 6: Log Dose
if [ -n "$MED_ID" ]; then
    echo "Test 6: Log Dose"
    curl -s -w "\nStatus: %{http_code}\n" -X POST \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $TOKEN" \
      -d '{"taken":true,"notes":"Taken with food"}' \
      "$BASE_URL/api/medications/$MED_ID/log"
    echo ""
fi

# Test 7: Get Adherence
if [ -n "$MED_ID" ]; then
    echo "Test 7: Get Adherence"
    curl -s -w "\nStatus: %{http_code}\n" \
      -H "Authorization: Bearer $TOKEN" \
      "$BASE_URL/api/medications/$MED_ID/adherence"
    echo ""
fi

# Test 8: Unauthorized Access
echo "Test 8: Unauthorized Access (should be 401)"
curl -s -w "\nStatus: %{http_code}\n" \
  "$BASE_URL/api/medications"
echo ""

# Test 9: Get User Profile
echo "Test 9: Get User Profile"
curl -s -w "\nStatus: %{http_code}\n" \
  -H "Authorization: Bearer $TOKEN" \
  "$BASE_URL/api/users/me"
echo ""

# Test 10: List Shares
echo "Test 10: List Shares"
curl -s -w "\nStatus: %{http_code}\n" \
  -H "Authorization: Bearer $TOKEN" \
  "$BASE_URL/api/shares"
echo ""

echo "=== Tests Complete ==="
