#!/bin/bash
# =============================================================================
# Presence Service - Rebuild Kafka Script
# =============================================================================
# Rebuilds Kafka container to apply new configuration.
# =============================================================================

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

echo -e "${YELLOW}🔄 Rebuilding Kafka containers...${NC}"
echo ""

cd "$PROJECT_DIR"

# 1. Stop Presence Service (if running)
echo -e "${BLUE}Step 1: Stop Presence Service${NC}"
PID=$(lsof -ti :3011 2>/dev/null)
if [ ! -z "$PID" ]; then
    echo "Stopping Presence Service (PID: $PID)..."
    kill $PID 2>/dev/null || true
    sleep 2
    echo -e "${GREEN}✓ Presence Service stopped${NC}"
else
    echo -e "${YELLOW}⚠️  Presence Service is not running${NC}"
fi
echo ""

# 2. Stop and remove Kafka and Zookeeper containers
echo -e "${BLUE}Step 2: Stop and remove old containers${NC}"
docker compose -f docker-compose.dev.yml stop kafka zookeeper 2>/dev/null || true
docker compose -f docker-compose.dev.yml rm -f kafka zookeeper 2>/dev/null || true
echo -e "${GREEN}✓ Old containers removed${NC}"
echo ""

# 3. Recreate containers
echo -e "${BLUE}Step 3: Create new containers${NC}"
docker compose -f docker-compose.dev.yml up -d zookeeper
echo "Waiting for Zookeeper to start..."
sleep 5

docker compose -f docker-compose.dev.yml up -d kafka
echo "Waiting for Kafka to start..."
sleep 20
echo -e "${GREEN}✓ Kafka containers created${NC}"
echo ""

# 4. Verify configuration
echo -e "${BLUE}Step 4: Verify configuration${NC}"
CONTAINER_NAME=$(docker ps --filter "name=presence-kafka" --format "{{.Names}}" | head -1)

if [ -z "$CONTAINER_NAME" ]; then
    echo -e "${RED}✗ Kafka container not found${NC}"
    exit 1
fi

echo "Container: $CONTAINER_NAME"

# Check if Kafka is responding
if docker exec "$CONTAINER_NAME" nc -z localhost 29092 2>/dev/null; then
    echo -e "${GREEN}✓ Kafka internal port (29092) is accessible${NC}"
else
    echo -e "${YELLOW}⚠️  Kafka internal port not yet available${NC}"
fi
echo ""

# 5. Test external connection
echo -e "${BLUE}Step 5: Test Kafka connection${NC}"
if nc -zv localhost 9092 2>&1 | grep -q "succeeded\|Connected"; then
    echo -e "${GREEN}✓ Kafka external port (9092) is accessible${NC}"
else
    echo -e "${YELLOW}⚠️  Kafka external port may need more time to start${NC}"
fi
echo ""

echo -e "${YELLOW}======================================${NC}"
echo -e "${GREEN}✓ Kafka rebuild complete!${NC}"
echo -e "${YELLOW}======================================${NC}"
echo ""
echo -e "${BLUE}Next steps:${NC}"
echo "1. Start Presence Service: npm run start:dev"
echo "2. Run health check: ./scripts/health-check.sh"
echo "3. Run quick tests: ./scripts/quick-test.sh"
