#!/bin/bash

echo "======================================"
echo "  FIXING 403 FORBIDDEN - DELETE ISSUE"
echo "======================================"
echo ""

# Step 1: Deploy Nginx config
echo "Step 1: Deploying 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

# Remove any conflicting configs
sudo rm -f /etc/nginx/sites-enabled/default 2>/dev/null
sudo rm -f /etc/nginx/sites-enabled/church-music 2>/dev/null

echo "Testing Nginx config..."
if sudo nginx -t 2>&1; then
    echo "✅ Nginx config valid"
else
    echo "❌ Nginx config has errors!"
    exit 1
fi

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

# Step 3: Restart Backend
echo ""
echo "Step 3: Restarting backend..."
sudo systemctl restart church-music-backend
sleep 3

if sudo systemctl is-active --quiet church-music-backend; then
    echo "✅ Backend is running"
else
    echo "❌ Backend failed to start!"
    sudo journalctl -u church-music-backend -n 20 --no-pager
    exit 1
fi

# Step 4: Test health
echo ""
echo "Step 4: Testing endpoints..."
echo ""

HEALTH=$(curl -s http://localhost:8080/health)
echo "Backend health: $HEALTH"

# Step 5: Test DELETE via HTTPS
echo ""
echo "Step 5: Testing DELETE endpoint..."

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

if [ -z "$TOKEN" ]; then
    echo "❌ Could not get auth token"
    exit 1
fi

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

# Test 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 "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | head -n-1)

echo ""
echo "DELETE Response:"
echo "  Status: $HTTP_CODE"
echo "  Body: $BODY"

if [ "$HTTP_CODE" = "200" ]; then
    echo ""
    echo "✅ SUCCESS! DELETE endpoint is working!"
    echo "Try removing a song from the worship list now!"
elif [ "$HTTP_CODE" = "403" ]; then
    echo ""
    echo "❌ Still getting 403 - check Nginx error logs:"
    sudo tail -10 /var/log/nginx/error.log
else
    echo ""
    echo "⚠️ Got status: $HTTP_CODE"
fi

echo ""
echo "======================================"
echo "Done!"
echo "======================================"
