#!/bin/bash

echo "============================================"
echo "Testing DELETE Endpoint for 403 Issue"
echo "============================================"
echo ""

# Step 1: Login and get token
echo "Step 1: Getting authentication token..."
LOGIN_RESPONSE=$(curl -s -X POST https://houseofprayer.ddns.net/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"hop","password":"hopWorship2024"}')

TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"token":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
    echo "❌ Failed to get token!"
    echo "Login response: $LOGIN_RESPONSE"
    exit 1
fi

echo "✅ Got token: ${TOKEN:0:30}..."
echo ""

# Step 2: Test the exact DELETE endpoint that's failing
echo "Step 2: Testing DELETE endpoint..."
echo "URL: https://houseofprayer.ddns.net/api/lists/24474ea3-6f34-4704-ac48-a80e1225d79e/songs/9831e027-aeb1-48a0-8763-fd3120f29692"
echo ""

DELETE_RESPONSE=$(curl -s -w "\n%{http_code}" -X DELETE \
  "https://houseofprayer.ddns.net/api/lists/24474ea3-6f34-4704-ac48-a80e1225d79e/songs/9831e027-aeb1-48a0-8763-fd3120f29692" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json")

HTTP_CODE=$(echo "$DELETE_RESPONSE" | tail -n1)
RESPONSE_BODY=$(echo "$DELETE_RESPONSE" | head -n-1)

echo "HTTP Status: $HTTP_CODE"
echo "Response Body: $RESPONSE_BODY"
echo ""

if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "204" ]; then
    echo "✅ SUCCESS! Endpoint is working!"
elif [ "$HTTP_CODE" = "403" ]; then
    echo "❌ STILL GETTING 403 FORBIDDEN"
    echo ""
    echo "This means:"
    echo "  - Backend hasn't been restarted with new code, OR"
    echo "  - There's another issue blocking the request"
elif [ "$HTTP_CODE" = "401" ]; then
    echo "⚠️  Got 401 Unauthorized"
    echo "Token might be invalid or expired"
else
    echo "⚠️  Got unexpected status: $HTTP_CODE"
fi

echo ""
echo "============================================"
echo "Step 3: Checking backend service status..."
echo "============================================"
echo ""

if systemctl is-active --quiet church-music-backend.service; then
    echo "✅ Backend service is running"
    echo ""
    echo "Last 10 lines from service journal:"
    journalctl -u church-music-backend.service -n 10 --no-pager 2>/dev/null || echo "(Could not read journal)"
else
    echo "❌ Backend service is NOT running!"
    echo "Run: sudo systemctl start church-music-backend.service"
fi

echo ""
echo "============================================"
echo "MANUAL RESTART COMMAND:"
echo "sudo systemctl restart church-music-backend.service"
echo "============================================"
