#!/bin/bash
# Enhanced Profile Management Test Script

BASE_URL="http://10.0.10.30:6500"

echo "🧪 Enhanced Profile Management Test"
echo "===================================="
echo ""

EMAIL="profiletest@example.com"
USERNAME="profiletest"
PASSWORD="SecurePassword123!"
NEW_USERNAME="updateduser"

echo "0. Register test user..."
REGISTER=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X POST $BASE_URL/api/auth/register \
  -H "Content-Type: application/json" \
  -d "{
    \"email\": \"$EMAIL\",
    \"username\": \"$USERNAME\",
    \"password\": \"$PASSWORD\",
    \"recovery_phrase\": \"test-recovery-phrase\"
  }")
echo "$REGISTER"
echo ""

echo "1. Login to get access token..."
LOGIN_RESPONSE=$(curl -s -X POST $BASE_URL/api/auth/login \
  -H "Content-Type: application/json" \
  -d "{
    \"email\": \"$EMAIL\",
    \"password\": \"$PASSWORD\"
  }")

echo "$LOGIN_RESPONSE" | jq .

ACCESS_TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.access_token // empty')

if [ -z "$ACCESS_TOKEN" ] || [ "$ACCESS_TOKEN" = "null" ]; then
    echo "❌ Failed to get access token"
    exit 1
fi

echo "✅ Access token obtained"
echo ""

echo "2. Get user profile..."
GET_PROFILE=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X GET $BASE_URL/api/users/me \
  -H "Authorization: Bearer $ACCESS_TOKEN")
echo "$GET_PROFILE"
echo ""

echo "3. Update profile (change username)..."
UPDATE_PROFILE=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X PUT $BASE_URL/api/users/me \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -d "{
    \"username\": \"$NEW_USERNAME\"
  }")
echo "$UPDATE_PROFILE"
echo ""

echo "4. Get profile again to verify update..."
GET_PROFILE_UPDATED=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X GET $BASE_URL/api/users/me \
  -H "Authorization: Bearer $ACCESS_TOKEN")
echo "$GET_PROFILE_UPDATED"
echo ""

echo "5. Try to access protected endpoint without token (should fail)..."
NO_TOKEN=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X GET $BASE_URL/api/users/me)
echo "$NO_TOKEN"
echo ""

echo "6. Try to delete account with wrong password (should fail)..."
WRONG_PASSWORD=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X DELETE $BASE_URL/api/users/me \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -d '{
    "password": "WrongPassword123!"
  }')
echo "$WRONG_PASSWORD"
echo ""

echo "7. Delete account with correct password..."
DELETE_ACCOUNT=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X DELETE $BASE_URL/api/users/me \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -d "{
    \"password\": \"$PASSWORD\"
  }")
echo "$DELETE_ACCOUNT"
echo ""

echo "8. Try to access profile after deletion (should fail)..."
AFTER_DELETE=$(curl -s -w "\nHTTP Status: %{http_code}\n" -X GET $BASE_URL/api/users/me \
  -H "Authorization: Bearer $ACCESS_TOKEN")
echo "$AFTER_DELETE"
echo ""

echo "✅ All profile management tests complete!"
