#!/bin/bash
# Test the Save Changes functionality

echo "=== Testing Worship List Save Changes ==="
echo ""

# Get a token (replace with your actual credentials)
echo "1. Getting auth token..."
TOKEN=$(curl -s -X POST "http://localhost:8080/api/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin"}' | jq -r '.token' 2>/dev/null)

if [ "$TOKEN" = "null" ] || [ -z "$TOKEN" ]; then
  echo "   ⚠ Could not get token (check credentials)"
  echo "   Using existing token from browser localStorage instead"
  echo ""
else
  echo "   ✓ Got token: ${TOKEN:0:20}..."
  echo ""
fi

# Get first worship list
echo "2. Getting worship lists..."
LIST_ID=$(curl -s "http://localhost:8080/api/lists" | jq -r '.lists[0].id' 2>/dev/null)

if [ "$LIST_ID" = "null" ] || [ -z "$LIST_ID" ]; then
  echo "   ✗ No worship lists found"
  exit 1
else
  echo "   ✓ Found list: $LIST_ID"
  echo ""
fi

# Get list details
echo "3. Getting list details..."
LIST_DETAILS=$(curl -s "http://localhost:8080/api/lists/$LIST_ID")
echo "   Current songs in list:"
echo "$LIST_DETAILS" | jq -r '.songs[] | "     - " + .title' 2>/dev/null
echo ""

# Test updating the list (if you have a token)
if [ "$TOKEN" != "null" ] && [ -n "$TOKEN" ]; then
  echo "4. Testing PUT /api/lists/$LIST_ID ..."
  
  # Get current song IDs
  SONG_IDS=$(echo "$LIST_DETAILS" | jq -c '[.songs[].id]' 2>/dev/null)
  
  RESULT=$(curl -s -X PUT "http://localhost:8080/api/lists/$LIST_ID" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{\"date\":\"2026-01-26\",\"profile_id\":\"4\",\"notes\":\"Test update\",\"songs\":$SONG_IDS}")
  
  if echo "$RESULT" | jq -e '.success' > /dev/null 2>&1; then
    echo "   ✓ Save Changes endpoint works!"
    echo "   Response: $(echo "$RESULT" | jq -c .)"
  else
    echo "   ✗ Save failed"
    echo "   Response: $RESULT"
  fi
else
  echo "4. Skipping PUT test (no token)"
  echo "   The endpoint is: PUT /api/lists/:id"
  echo "   Requires Authorization: Bearer <token>"
  echo "   Body: {date, profile_id, notes, songs: [song_ids]}"
fi

echo ""
echo "=== Test Complete ==="
