#!/bin/bash
# 重建 Kafka 容器以应用新的配置

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

echo -e "${YELLOW}🔄 重建 Kafka 容器...${NC}"
echo ""

# 1. 停止 Identity Service (如果在运行)
echo -e "${BLUE}步骤 1: 停止 Identity Service${NC}"
PID=$(lsof -ti :3000 2>/dev/null)
if [ ! -z "$PID" ]; then
    echo "停止 Identity Service (PID: $PID)..."
    kill $PID
    sleep 2
    echo -e "${GREEN}✓ Identity Service 已停止${NC}"
else
    echo -e "${YELLOW}⚠️  Identity Service 未在运行${NC}"
fi
echo ""

# 2. 停止并删除 Kafka 和 Zookeeper 容器
echo -e "${BLUE}步骤 2: 停止并删除旧容器${NC}"
docker compose stop kafka zookeeper
docker compose rm -f kafka zookeeper
echo -e "${GREEN}✓ 旧容器已删除${NC}"
echo ""

# 3. 重新创建容器
echo -e "${BLUE}步骤 3: 创建新容器${NC}"
docker compose up -d zookeeper
echo "等待 Zookeeper 启动..."
sleep 5

docker compose up -d kafka
echo "等待 Kafka 启动..."
sleep 20
echo -e "${GREEN}✓ Kafka 容器已创建${NC}"
echo ""

# 4. 验证新配置
echo -e "${BLUE}步骤 4: 验证配置${NC}"
ADVERTISED=$(docker inspect identity-service-kafka-1 2>/dev/null | grep -A 1 "KAFKA_ADVERTISED_LISTENERS" | head -1)

if echo "$ADVERTISED" | grep -q "localhost:9092"; then
    echo -e "${GREEN}✓ Kafka 配置已更新！${NC}"
    echo "$ADVERTISED"
else
    echo -e "${RED}✗ Kafka 配置仍然不正确${NC}"
    echo "$ADVERTISED"
    exit 1
fi
echo ""

# 5. 测试连接
echo -e "${BLUE}步骤 5: 测试 Kafka 连接${NC}"
if nc -zv localhost 9092 2>&1 | grep -q "succeeded"; then
    echo -e "${GREEN}✓ Kafka 端口可访问${NC}"
else
    echo -e "${RED}✗ Kafka 端口不可访问${NC}"
    exit 1
fi
echo ""

echo -e "${YELLOW}======================================${NC}"
echo -e "${GREEN}✓ Kafka 重建完成！${NC}"
echo -e "${YELLOW}======================================${NC}"
echo ""
echo -e "${BLUE}下一步：${NC}"
echo "1. 启动 Identity Service: npm run start:dev"
echo "2. 运行健康检查: ./scripts/health-check.sh"
echo "3. 运行快速测试: ./scripts/quick-test.sh"
