#!/bin/bash

echo "========================================="
echo "DEEP DEBUGGING - TechZone Admin Dashboard"
echo "========================================="
echo ""

# Test 1: Backend health
echo "1. Backend Health Check..."
HEALTH=$(curl -s http://localhost:8181/api/)
if echo "$HEALTH" | grep -q "TechZone API is running"; then
    echo "✅ Backend is responding"
else
    echo "❌ Backend health check failed"
    exit 1
fi
echo ""

# Test 2: Admin authentication
echo "2. Testing Admin Authentication..."
LOGIN=$(curl -s -X POST http://localhost:8181/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@techzone.com","password":"admin123"}')

if echo "$LOGIN" | grep -q "access_token"; then
    echo "✅ Admin login successful"
    TOKEN=$(echo $LOGIN | python3 -c "import sys, json; print(json.load(sys.stdin)['access_token'])")
else
    echo "❌ Admin login failed"
    echo "Response: $LOGIN"
    exit 1
fi
echo ""

# Test 3: Dashboard API call
echo "3. Testing Dashboard Endpoint..."
DASHBOARD=$(curl -s -w "\nHTTP_CODE:%{http_code}" \
  http://localhost:8181/api/admin/dashboard \
  -H "Authorization: Bearer $TOKEN")

HTTP_CODE=$(echo "$DASHBOARD" | grep "HTTP_CODE:" | cut -d: -f2)
RESPONSE=$(echo "$DASHBOARD" | sed '/HTTP_CODE:/d')

echo "HTTP Status: $HTTP_CODE"

if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ Dashboard API returned 200 OK"
    
    # Validate response structure
    echo "$RESPONSE" | python3 << 'PYEOF'
import sys, json

try:
    data = json.load(sys.stdin)
    
    # Check required fields
    assert "stats" in data, "Missing 'stats' field"
    assert "low_stock_products" in data, "Missing 'low_stock_products' field"
    assert "recent_orders" in data, "Missing 'recent_orders' field"
    
    # Check stats structure
    stats = data["stats"]
    required_stats = [
        "total_products", "total_services", "total_users", "total_orders",
        "total_revenue", "monthly_revenue", "today_orders", "today_revenue",
        "pending_bookings"
    ]
    
    for stat in required_stats:
        assert stat in stats, f"Missing stat: {stat}"
        assert isinstance(stats[stat], (int, float)), f"Invalid type for {stat}"
    
    print("✅ Response structure is valid")
    print(f"   Stats fields: {len(stats)}")
    print(f"   Low stock products: {len(data['low_stock_products'])}")
    print(f"   Recent orders: {len(data['recent_orders'])}")
    
except Exception as e:
    print(f"❌ Response validation failed: {e}")
    sys.exit(1)
PYEOF
    
else
    echo "❌ Dashboard API failed with status $HTTP_CODE"
    echo "Response: $RESPONSE"
    exit 1
fi
echo ""

# Test 4: CORS headers
echo "4. Testing CORS Headers..."
CORS=$(curl -s -I -H "Origin: http://localhost:5300" \
  -H "Authorization: Bearer $TOKEN" \
  http://localhost:8181/api/admin/dashboard | grep -i "access-control")

if [ -n "$CORS" ]; then
    echo "✅ CORS headers present:"
    echo "$CORS"
else
    echo "⚠️  No CORS headers found (may cause browser issues)"
fi
echo ""

# Test 5: Frontend connectivity
echo "5. Testing Frontend Server..."
FRONTEND=$(curl -s -I http://localhost:5300 | head -1)
if echo "$FRONTEND" | grep -q "200 OK"; then
    echo "✅ Frontend is serving"
else
    echo "❌ Frontend not responding properly"
    echo "Response: $FRONTEND"
fi
echo ""

# Test 6: Token expiry check
echo "6. Checking Token Validity..."
TOKEN_INFO=$(echo $TOKEN | cut -d. -f2 | base64 -d 2>/dev/null)
if [ $? -eq 0 ]; then
    echo "✅ Token is properly formatted JWT"
    echo "$TOKEN_INFO" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    exp = data.get('exp', 'N/A')
    sub = data.get('sub', 'N/A')
    print(f'   Subject: {sub}')
    print(f'   Expires: {exp}')
except:
    pass
" 2>/dev/null || echo "   (Token payload details unavailable)"
else
    echo "⚠️  Token format check failed"
fi
echo ""

# Test 7: Database connectivity
echo "7. Testing Database Operations..."
PRODUCTS=$(curl -s http://localhost:8181/api/products -H "Authorization: Bearer $TOKEN")
if echo "$PRODUCTS" | python3 -c "import sys, json; len(json.load(sys.stdin))" >/dev/null 2>&1; then
    PRODUCT_COUNT=$(echo "$PRODUCTS" | python3 -c "import sys, json; print(len(json.load(sys.stdin)))")
    echo "✅ Database queries working (${PRODUCT_COUNT} products)"
else
    echo "❌ Database query failed"
fi
echo ""

echo "========================================="
echo "✅ DEEP DEBUG COMPLETE - No critical issues found"
echo "========================================="
