#!/bin/bash
# Test Save Changes functionality

echo "=== Testing Save Changes ==="

# Get auth token (you need to provide actual credentials)
read -p "Enter username (default: admin): " USERNAME
USERNAME=${USERNAME:-admin}
read -sp "Enter password: " PASSWORD
echo ""

TOKEN=$(curl -s -X POST "http://localhost:8080/api/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}" | jq -r '.token' 2>/dev/null)

if [ "$TOKEN" = "null" ] || [ -z "$TOKEN" ]; then
  echo "✗ Failed to get auth token"
  echo "  Check credentials or try the test manually in browser"
  exit 1
fi

echo "✓ Got auth token"
echo ""

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

# Get current songs
SONGS=$(curl -s "http://localhost:8080/api/lists/$LIST_ID" | jq -c '[.songs[].id]' 2>/dev/null)
echo "Current songs: $SONGS"
echo ""

# Try to update (PUT request)
echo "Sending PUT request..."
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 save changes\",
    \"songs\": $SONGS
  }")

echo "Response:"
echo "$RESULT" | jq '.' 2>/dev/null || echo "$RESULT"
echo ""

if echo "$RESULT" | jq -e '.success' > /dev/null 2>&1; then
  echo "✓ Save Changes works!"
else
  echo "✗ Save Changes failed"
  echo ""
  echo "Check backend logs:"
  tail -30 /tmp/backend-new.log
fi
