#!/bin/bash

# Redis Failover Test Script
# This script tests the failover mechanism by simulating Redis failure

echo "🧪 Redis Failover Test"
echo "====================="
echo ""

# Check if Redis is running
echo "1️⃣ Checking Redis status..."
if docker exec cbt-redis redis-cli ping > /dev/null 2>&1; then
    echo "   ✅ Redis is running"
else
    echo "   ❌ Redis is not running. Please start Redis first."
    exit 1
fi

echo ""
echo "2️⃣ Stopping Redis to simulate failure..."
docker stop cbt-redis
sleep 5

echo ""
echo "3️⃣ Testing application failover..."
# Try to access the application
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/health 2>/dev/null)

if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "302" ]; then
    echo "   ✅ Application is still accessible (HTTP $HTTP_CODE)"
    echo "   ✅ Failover is working - using database cache"
else
    echo "   ⚠️  Application returned HTTP $HTTP_CODE"
fi

echo ""
echo "4️⃣ Restarting Redis..."
docker start cbt-redis
sleep 10

echo ""
echo "5️⃣ Verifying Redis is back..."
if docker exec cbt-redis redis-cli ping > /dev/null 2>&1; then
    echo "   ✅ Redis is running again"
    echo "   ✅ Application should switch back to Redis cache"
else
    echo "   ❌ Redis failed to start"
fi

echo ""
echo "✨ Test complete!"
echo ""
echo "📝 Summary:"
echo "   - Redis was stopped to simulate failure"
echo "   - Application should have switched to database cache"
echo "   - Redis was restarted"
echo "   - Application should switch back to Redis"
echo ""
echo "💡 Tip: Check application logs to see the failover in action"