#!/bin/bash
# Test script to verify profile songs endpoint

echo "�� Testing Profile Songs Endpoint..."
echo "======================================"

# Check if backend is running
if ! curl -s http://localhost:5000/api/songs > /dev/null 2>&1; then
    echo "❌ Backend is not running on port 5000!"
    echo "Please start the backend first: cd backend && python3 app.py"
    exit 1
fi

echo "✅ Backend is running"
echo ""

# Get first profile
echo "📋 Fetching profiles..."
PROFILE_ID=$(curl -s http://localhost:5000/api/profiles | python3 -c "import sys, json; profiles = json.load(sys.stdin); print(profiles[0]['id'] if profiles else 'none')" 2>/dev/null)

if [ "$PROFILE_ID" = "none" ] || [ -z "$PROFILE_ID" ]; then
    echo "⚠️  No profiles found. Create a profile first."
    exit 0
fi

echo "✅ Found profile: $PROFILE_ID"
echo ""

# Test profile songs endpoint
echo "🎵 Testing GET /api/profiles/$PROFILE_ID/songs"
RESPONSE=$(curl -s "http://localhost:5000/api/profiles/$PROFILE_ID/songs")
echo "Response: $RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$RESPONSE"
echo ""

# Check if response is valid JSON array
IS_ARRAY=$(echo "$RESPONSE" | python3 -c "import sys, json; data = json.load(sys.stdin); print('yes' if isinstance(data, list) else 'no')" 2>/dev/null)

if [ "$IS_ARRAY" = "yes" ]; then
    COUNT=$(echo "$RESPONSE" | python3 -c "import sys, json; print(len(json.load(sys.stdin)))" 2>/dev/null)
    echo "✅ API returned valid array with $COUNT songs"
    
    if [ "$COUNT" -gt 0 ]; then
        echo ""
        echo "📝 First song structure:"
        echo "$RESPONSE" | python3 -c "import sys, json; data = json.load(sys.stdin); print(json.dumps(data[0], indent=2))" 2>/dev/null
    fi
else
    echo "❌ API did not return a valid array"
fi

echo ""
echo "✅ Test complete!"
