#!/bin/bash

# ========================================
# Docker 迁移功能自动测试脚本
# ========================================

set -e  # 遇到错误立即退出

echo "🚀 开始Docker迁移功能自动测试..."
echo "=================================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 错误计数
ERROR_COUNT=0

# 记录错误函数
record_error() {
    echo -e "${RED}❌ 错误: $1${NC}"
    ERROR_COUNT=$((ERROR_COUNT + 1))
}

# 记录成功函数
record_success() {
    echo -e "${GREEN}✅ 成功: $1${NC}"
}

# 记录警告函数
record_warning() {
    echo -e "${YELLOW}⚠️  警告: $1${NC}"
}

# 记录信息函数
record_info() {
    echo -e "${BLUE}ℹ️  信息: $1${NC}"
}

echo "📋 测试阶段1: 环境准备"
echo "=================================================="

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    record_error "Docker未运行，请启动Docker"
    exit 1
fi
record_success "Docker运行正常"

# 检查Docker Compose是否可用
if ! docker-compose --version > /dev/null 2>&1; then
    record_error "Docker Compose不可用"
    exit 1
fi
record_success "Docker Compose可用"

# 停止并清理现有容器
record_info "清理现有容器..."
docker-compose down -v --remove-orphans > /dev/null 2>&1 || true
record_success "现有容器已清理"

echo ""
echo "📋 测试阶段2: 迁移工具测试"
echo "=================================================="

# 测试迁移工具
record_info "测试迁移工具..."
cd tools

# 测试PHP文件发现工具
if node -e "const PHPFileDiscovery = require('./php-file-discovery.js'); const discovery = new PHPFileDiscovery(); discovery.run(); console.log('PHP文件发现工具测试通过');" 2>/dev/null; then
    record_success "PHP文件发现工具正常"
else
    record_error "PHP文件发现工具失败"
fi

# 测试业务逻辑转换器
if node -e "const BusinessLogicConverter = require('./generators/business-logic-converter.js'); const converter = new BusinessLogicConverter(); console.log('业务逻辑转换器测试通过');" 2>/dev/null; then
    record_success "业务逻辑转换器正常"
else
    record_error "业务逻辑转换器失败"
fi

# 测试控制器生成器
if node -e "const ControllerGenerator = require('./generators/controller-generator.js'); const generator = new ControllerGenerator(); console.log('控制器生成器测试通过');" 2>/dev/null; then
    record_success "控制器生成器正常"
else
    record_error "控制器生成器失败"
fi

# 测试服务生成器
if node -e "const ServiceGenerator = require('./generators/service-generator.js'); const generator = new ServiceGenerator(); console.log('服务生成器测试通过');" 2>/dev/null; then
    record_success "服务生成器正常"
else
    record_error "服务生成器失败"
fi

# 测试实体生成器
if node -e "const EntityGenerator = require('./generators/entity-generator.js'); const generator = new EntityGenerator(); console.log('实体生成器测试通过');" 2>/dev/null; then
    record_success "实体生成器正常"
else
    record_error "实体生成器失败"
fi

# 测试迁移协调器
if node -e "const MigrationCoordinator = require('./migration-coordinator.js'); const coordinator = new MigrationCoordinator(); console.log('迁移协调器测试通过');" 2>/dev/null; then
    record_success "迁移协调器正常"
else
    record_error "迁移协调器失败"
fi

cd ..

echo ""
echo "📋 测试阶段3: 构建Docker镜像"
echo "=================================================="

# 构建NestJS后端镜像
record_info "构建NestJS后端镜像..."
if docker-compose build nestjs-backend; then
    record_success "NestJS后端镜像构建成功"
else
    record_error "NestJS后端镜像构建失败"
fi

# 构建Admin前端镜像
record_info "构建Admin前端镜像..."
if docker-compose build admin-frontend; then
    record_success "Admin前端镜像构建成功"
else
    record_error "Admin前端镜像构建失败"
fi

echo ""
echo "📋 测试阶段4: 启动服务"
echo "=================================================="

# 启动基础服务（MySQL和Redis）
record_info "启动MySQL和Redis服务..."
if docker-compose up -d mysql redis; then
    record_success "MySQL和Redis服务启动成功"
else
    record_error "MySQL和Redis服务启动失败"
fi

# 等待数据库就绪
record_info "等待数据库就绪..."
sleep 30

# 检查MySQL健康状态
if docker-compose exec -T mysql mysqladmin ping -h localhost -u root -proot123456 > /dev/null 2>&1; then
    record_success "MySQL数据库连接正常"
else
    record_error "MySQL数据库连接失败"
fi

# 检查Redis健康状态
if docker-compose exec -T redis redis-cli -a redis123456 ping > /dev/null 2>&1; then
    record_success "Redis缓存连接正常"
else
    record_error "Redis缓存连接失败"
fi

echo ""
echo "📋 测试阶段5: 启动NestJS后端"
echo "=================================================="

# 启动NestJS后端
record_info "启动NestJS后端服务..."
if docker-compose up -d nestjs-backend; then
    record_success "NestJS后端服务启动成功"
else
    record_error "NestJS后端服务启动失败"
fi

# 等待NestJS服务就绪
record_info "等待NestJS服务就绪..."
sleep 60

# 检查NestJS健康状态
if curl -f http://localhost:3000/health > /dev/null 2>&1; then
    record_success "NestJS后端健康检查通过"
else
    record_error "NestJS后端健康检查失败"
    # 显示NestJS日志
    record_info "NestJS服务日志:"
    docker-compose logs nestjs-backend --tail=50
fi

echo ""
echo "📋 测试阶段6: 启动Admin前端"
echo "=================================================="

# 启动Admin前端
record_info "启动Admin前端服务..."
if docker-compose up -d admin-frontend; then
    record_success "Admin前端服务启动成功"
else
    record_error "Admin前端服务启动失败"
fi

# 等待Admin前端就绪
record_info "等待Admin前端就绪..."
sleep 30

# 检查Admin前端健康状态
if curl -f http://localhost/ > /dev/null 2>&1; then
    record_success "Admin前端健康检查通过"
else
    record_error "Admin前端健康检查失败"
    # 显示Admin前端日志
    record_info "Admin前端服务日志:"
    docker-compose logs admin-frontend --tail=50
fi

echo ""
echo "📋 测试阶段7: API接口测试"
echo "=================================================="

# 测试关键API接口
record_info "测试关键API接口..."

# 测试健康检查接口
if curl -f http://localhost:3000/health > /dev/null 2>&1; then
    record_success "健康检查接口正常"
else
    record_error "健康检查接口失败"
fi

# 测试API根路径
if curl -f http://localhost:3000/api > /dev/null 2>&1; then
    record_success "API根路径正常"
else
    record_warning "API根路径可能未配置"
fi

# 测试Admin API路径
if curl -f http://localhost:3000/adminapi > /dev/null 2>&1; then
    record_success "Admin API路径正常"
else
    record_warning "Admin API路径可能未配置"
fi

echo ""
echo "📋 测试阶段8: 数据库连接测试"
echo "=================================================="

# 测试数据库连接
record_info "测试数据库连接..."
if docker-compose exec -T nestjs-backend node -e "
const mysql = require('mysql2/promise');
async function test() {
  try {
    const connection = await mysql.createConnection({
      host: 'mysql',
      user: 'wwjcloud',
      password: 'wwjcloud123',
      database: 'wwjcloud'
    });
    await connection.execute('SELECT 1');
    await connection.end();
    console.log('数据库连接测试成功');
  } catch (error) {
    console.error('数据库连接测试失败:', error.message);
    process.exit(1);
  }
}
test();
" 2>/dev/null; then
    record_success "数据库连接测试通过"
else
    record_error "数据库连接测试失败"
fi

echo ""
echo "📋 测试阶段9: 服务状态检查"
echo "=================================================="

# 检查所有服务状态
record_info "检查所有服务状态..."
docker-compose ps

echo ""
echo "📋 测试阶段10: 日志检查"
echo "=================================================="

# 检查NestJS日志中的错误
record_info "检查NestJS服务日志..."
NESTJS_ERRORS=$(docker-compose logs nestjs-backend 2>&1 | grep -i "error\|exception\|failed" | wc -l)
if [ "$NESTJS_ERRORS" -eq 0 ]; then
    record_success "NestJS服务无错误日志"
else
    record_warning "NestJS服务发现 $NESTJS_ERRORS 个错误日志"
    docker-compose logs nestjs-backend 2>&1 | grep -i "error\|exception\|failed" | head -10
fi

# 检查Admin前端日志中的错误
record_info "检查Admin前端日志..."
ADMIN_ERRORS=$(docker-compose logs admin-frontend 2>&1 | grep -i "error\|exception\|failed" | wc -l)
if [ "$ADMIN_ERRORS" -eq 0 ]; then
    record_success "Admin前端无错误日志"
else
    record_warning "Admin前端发现 $ADMIN_ERRORS 个错误日志"
    docker-compose logs admin-frontend 2>&1 | grep -i "error\|exception\|failed" | head -10
fi

echo ""
echo "📊 测试结果汇总"
echo "=================================================="

if [ $ERROR_COUNT -eq 0 ]; then
    echo -e "${GREEN}🎉 所有测试通过！迁移功能完全正常！${NC}"
    echo -e "${GREEN}✅ 错误数量: 0${NC}"
    echo -e "${GREEN}✅ 迁移工具: 正常${NC}"
    echo -e "${GREEN}✅ Docker构建: 成功${NC}"
    echo -e "${GREEN}✅ 服务启动: 成功${NC}"
    echo -e "${GREEN}✅ API接口: 正常${NC}"
    echo -e "${GREEN}✅ 数据库连接: 正常${NC}"
else
    echo -e "${RED}❌ 测试发现问题！${NC}"
    echo -e "${RED}❌ 错误数量: $ERROR_COUNT${NC}"
    echo -e "${YELLOW}⚠️  请检查上述错误信息并修复${NC}"
fi

echo ""
echo "📋 服务访问信息"
echo "=================================================="
echo -e "${BLUE}🌐 Admin前端: http://localhost${NC}"
echo -e "${BLUE}🔧 NestJS后端: http://localhost:3000${NC}"
echo -e "${BLUE}💾 MySQL数据库: localhost:3306${NC}"
echo -e "${BLUE}🗄️  Redis缓存: localhost:6379${NC}"

echo ""
echo "📋 清理命令"
echo "=================================================="
echo -e "${YELLOW}停止所有服务: docker-compose down${NC}"
echo -e "${YELLOW}停止并清理数据: docker-compose down -v${NC}"
echo -e "${YELLOW}查看服务日志: docker-compose logs [service-name]${NC}"

# 如果测试失败，退出码为1
if [ $ERROR_COUNT -gt 0 ]; then
    exit 1
fi

echo ""
echo -e "${GREEN}🎊 Docker迁移功能自动测试完成！${NC}"
