#!/bin/bash
# 一键启动所有服务

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${YELLOW}🚀 启动所有服务...${NC}"
echo ""

# 1. 启动 Redis
echo -e "${YELLOW}启动 Redis...${NC}"
if ! pgrep -x "redis-server" > /dev/null; then
    redis-server --daemonize yes
    echo -e "${GREEN}✓ Redis 已启动${NC}"
else
    echo -e "${GREEN}✓ Redis 已在运行${NC}"
fi

# 2. 检查 PostgreSQL
echo -e "${YELLOW}检查 PostgreSQL...${NC}"
if pg_isready -h localhost -p 5432 > /dev/null 2>&1; then
    echo -e "${GREEN}✓ PostgreSQL 已在运行${NC}"
else
    echo -e "${YELLOW}⚠ PostgreSQL 未运行，请手动启动${NC}"
fi

# 3. 检查 Kafka
echo -e "${YELLOW}检查 Kafka...${NC}"
if nc -zv localhost 9092 > /dev/null 2>&1; then
    echo -e "${GREEN}✓ Kafka 已在运行${NC}"
else
    echo -e "${YELLOW}⚠ Kafka 未运行，请手动启动${NC}"
fi

# 4. 启动 Identity Service
echo -e "${YELLOW}启动 Identity Service...${NC}"
cd "$(dirname "$0")/.."
npm run start:dev &

# 等待服务启动
echo "等待服务启动 (最多 30 秒)..."
for i in {1..30}; do
    if curl -f http://localhost:3000/health > /dev/null 2>&1; then
        echo -e "${GREEN}✓ Identity Service 已启动${NC}"
        break
    fi
    sleep 1
    echo -n "."
done

echo ""
echo -e "${GREEN}✓ 所有服务已启动！${NC}"
echo ""
echo "运行健康检查："
echo "  ./scripts/health-check.sh"
echo ""
echo "运行快速测试："
echo "  ./scripts/quick-test.sh"
