#!/bin/bash

echo "╔════════════════════════════════════════════╗"
echo "║  FINAL VERIFICATION - All Safeguards      ║"
echo "╚════════════════════════════════════════════╝"
echo ""

# Test 1: Health Check
echo "1. Health Check Endpoint..."
HEALTH=$(curl -s http://localhost:8181/api/health)
if echo "$HEALTH" | grep -q '"status": "healthy"'; then
    echo "✅ Health check: System healthy"
    echo "$HEALTH" | python3 -m json.tool | head -5
else
    echo "❌ Health check failed"
fi
echo ""

# Test 2: Invalid Token Handling
echo "2. Testing Invalid Token Handling..."
INVALID=$(curl -s -w "\nSTATUS:%{http_code}" \
    http://localhost:8181/api/admin/dashboard \
    -H "Authorization: Bearer invalid_token_12345")
STATUS=$(echo "$INVALID" | grep "STATUS:" | cut -d: -f2)
if [ "$STATUS" = "401" ]; then
    echo "✅ Invalid token properly rejected (401)"
else
    echo "❌ Invalid token not handled (got $STATUS)"
fi
echo ""

# Test 3: Missing Token Handling
echo "3. Testing Missing Token..."
MISSING=$(curl -s -w "\nSTATUS:%{http_code}" \
    http://localhost:8181/api/admin/dashboard)
STATUS=$(echo "$MISSING" | grep "STATUS:" | cut -d: -f2)
if [ "$STATUS" = "403" ] || [ "$STATUS" = "401" ]; then
    echo "✅ Missing token blocked ($STATUS)"
else
    echo "❌ Missing token not handled (got $STATUS)"
fi
echo ""

# Test 4: Valid Admin Access
echo "4. Testing Valid Admin Access..."
TOKEN=$(curl -s -X POST http://localhost:8181/api/auth/login \
    -H "Content-Type: application/json" \
    -d '{"email":"admin@techzone.com","password":"admin123"}' \
    | python3 -c "import sys, json; print(json.load(sys.stdin)['access_token'])")

DASHBOARD=$(curl -s -w "\nSTATUS:%{http_code}" \
    http://localhost:8181/api/admin/dashboard \
    -H "Authorization: Bearer $TOKEN")
STATUS=$(echo "$DASHBOARD" | grep "STATUS:" | cut -d: -f2)
RESPONSE=$(echo "$DASHBOARD" | sed '/STATUS:/d')

if [ "$STATUS" = "200" ]; then
    echo "✅ Admin access granted (200)"
    
    # Validate response structure
    echo "$RESPONSE" | python3 << 'PYEOF'
import sys, json

data = json.load(sys.stdin)
checks = []

# Check all required fields
checks.append(("stats field", "stats" in data))
checks.append(("low_stock_products field", "low_stock_products" in data))
checks.append(("recent_orders field", "recent_orders" in data))

# Check stats completeness
if "stats" in data:
    stats = data["stats"]
    required = ["total_products", "total_services", "total_users", 
                "total_orders", "total_revenue", "monthly_revenue",
                "today_orders", "today_revenue", "pending_bookings"]
    for stat in required:
        checks.append((f"stat: {stat}", stat in stats))

# Print results
passed = sum(1 for _, result in checks if result)
total = len(checks)

for check_name, result in checks:
    symbol = "✅" if result else "❌"
    print(f"  {symbol} {check_name}")

print(f"\n  Summary: {passed}/{total} checks passed")

if passed == total:
    print("  ✅ All response structure checks passed!")
    sys.exit(0)
else:
    print("  ❌ Some checks failed")
    sys.exit(1)
PYEOF
else
    echo "❌ Admin access failed (got $STATUS)"
fi
echo ""

# Test 5: Error Recovery
echo "5. Testing Error Recovery (graceful degradation)..."
# Dashboard should return data even if some queries fail
if echo "$RESPONSE" | python3 -c "import sys, json; d=json.load(sys.stdin); exit(0 if all(k in d['stats'] for k in ['total_products', 'total_users']) else 1)" 2>/dev/null; then
    echo "✅ Error recovery working (returns safe defaults)"
else
    echo "❌ Error recovery issue detected"
fi
echo ""

# Test 6: Logging Verification
echo "6. Checking Enhanced Logging..."
if grep -q "Database connection verified" /media/pts/Website/PromptTech_Solution_Site/backend/server.log; then
    echo "✅ Enhanced logging active"
    echo "   Recent log entries:"
    tail -3 /media/pts/Website/PromptTech_Solution_Site/backend/server.log | sed 's/^/     /'
else
    echo "⚠️  Enhanced logging may not be active"
fi
echo ""

# Test 7: All Admin Endpoints
echo "7. Testing All Admin Endpoints..."
endpoints=(
    "GET /api/admin/dashboard"
    "GET /api/admin/products"
    "GET /api/admin/services"
    "GET /api/admin/orders"
    "GET /api/admin/inventory"
    "GET /api/admin/bookings"
)

for endpoint in "${endpoints[@]}"; do
    method=$(echo $endpoint | cut -d' ' -f1)
    path=$(echo $endpoint | cut -d' ' -f2)
    url="http://localhost:8181$path"
    
    if [ "$method" = "GET" ]; then
        STATUS=$(curl -s -w "%{http_code}" -o /dev/null \
            -H "Authorization: Bearer $TOKEN" "$url")
        if [ "$STATUS" = "200" ]; then
            echo "  ✅ $endpoint"
        else
            echo "  ❌ $endpoint (got $STATUS)"
        fi
    fi
done
echo ""

echo "╔════════════════════════════════════════════╗"
echo "║  ✅ VERIFICATION COMPLETE                 ║"
echo "║                                            ║"
echo "║  All safeguards operational!               ║"
echo "╚════════════════════════════════════════════╝"
