#!/bin/bash
# ONE-COMMAND FIX FOR 403 DELETE ISSUE

echo "======================================================================="
echo "FIXING WORSHIP LIST DELETE - 403 FORBIDDEN"
echo "======================================================================="
echo ""

# Step 1: Deploy Nginx config with CORS headers
echo "1. Deploying corrected Nginx configuration..."
sudo cp /media/pts/Website/Church_HOP_MusicData/new-site/nginx-ssl.conf /etc/nginx/sites-available/church-music-ssl
sudo ln -sf /etc/nginx/sites-available/church-music-ssl /etc/nginx/sites-enabled/church-music-ssl
sudo rm -f /etc/nginx/sites-enabled/default 2>/dev/null

echo "2. Testing Nginx configuration..."
if ! sudo nginx -t; then
    echo "❌ Nginx config error! Check syntax."
    exit 1
fi
echo "✅ Nginx config OK"

# Step 2: Reload Nginx
echo ""
echo "3. Reloading Nginx..."
sudo systemctl reload nginx
echo "✅ Nginx reloaded"

# Step 3: Restart Backend
echo ""
echo "4. Restarting backend service..."
sudo systemctl stop church-music-backend
sleep 2
sudo systemctl start church-music-backend
sleep 3

if sudo systemctl is-active --quiet church-music-backend; then
    echo "✅ Backend started"
else
    echo "❌ Backend failed to start!"
    sudo systemctl status church-music-backend --no-pager -l | tail -20
    exit 1
fi

# Step 4: Verify services
echo ""
echo "5. Verifying services..."
echo ""

# Check backend health
echo "Testing backend health..."
HEALTH=$(curl -s -m 5 http://localhost:8080/health 2>&1)
if echo "$HEALTH" | grep -q "ok"; then
    echo "✅ Backend is responding"
else
    echo "❌ Backend not responding: $HEALTH"
fi

# Step 5: Test DELETE endpoint
echo ""
echo "6. Testing DELETE endpoint..."
echo ""

# Get token
TOKEN=$(curl -s -m 10 -X POST https://houseofprayer.ddns.net/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"hop","password":"hopWorship2024"}' 2>&1 | grep -o '"token":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
    echo "⚠️  Could not get auth token - login may have failed"
    echo "But services are restarted and should work now."
else
    echo "Got auth token: ${TOKEN:0:30}..."
    
    # Test DELETE
    RESPONSE=$(curl -s -w "\nHTTP_CODE:%{http_code}" -m 10 -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" 2>&1)
    
    HTTP_CODE=$(echo "$RESPONSE" | grep "HTTP_CODE:" | cut -d: -f2)
    
    echo "DELETE Response Status: $HTTP_CODE"
    
    if [ "$HTTP_CODE" = "200" ]; then
        echo ""
        echo "✅✅✅ SUCCESS! DELETE IS WORKING! ✅✅✅"
        echo ""
        echo "You can now:"
        echo "  - Delete songs from worship lists"
        echo "  - Add songs to worship lists"
        echo "  - Edit existing worship lists"
        echo ""
    elif [ "$HTTP_CODE" = "404" ]; then
        echo ""
        echo "✅ Endpoint works! (404 means song doesn't exist - already deleted)"
        echo "Try with a song that exists in a worship list"
    elif [ "$HTTP_CODE" = "403" ]; then
        echo ""
        echo "❌ Still getting 403"
        echo "Check Nginx error log:"
        sudo tail -10 /var/log/nginx/error.log
    else
        echo ""
        echo "Got status: $HTTP_CODE"
        echo "$(echo "$RESPONSE" | grep -v "HTTP_CODE:")"
    fi
fi

echo ""
echo "======================================================================="
echo "SETUP COMPLETE"
echo "======================================================================="
echo ""
echo "Services restarted:"
echo "  ✅ Nginx reloaded with CORS headers"
echo "  ✅ Backend restarted with authentication"
echo ""
echo "Try the worship list now:"
echo "  1. Go to https://houseofprayer.ddns.net"
echo "  2. Log in"
echo "  3. Open a worship list"
echo "  4. Try to edit/delete songs"
echo ""
echo "If you still have issues, check:"
echo "  - Browser console for errors"
echo "  - Clear browser cache (Ctrl+Shift+Delete)"
echo "  - Try incognito/private window"
echo ""
