#!/bin/bash
# 数据库配置验证脚本
# 用于验证生产环境下后端服务是否正确连接到生产数据库

set -e

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

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否在正确的目录
check_directory() {
    if [[ ! -f "deploy.sh" ]]; then
        log_error "请在部署目录中运行此脚本 (应包含 deploy.sh)"
        exit 1
    fi
}

# 检查环境变量配置
check_environment_variables() {
    log_info "检查生产环境配置..."
    
    if [[ -f "environments/.env.production" ]]; then
        log_success "✓ 找到生产环境配置文件"
        
        # 显示数据库配置
        echo "数据库配置:"
        grep -E "^(DB_HOST|DB_PORT|DB_NAME|DB_USER|DB_PASSWORD)=" environments/.env.production | while read line; do
            if [[ $line == *"DB_PASSWORD"* ]]; then
                echo "  DB_PASSWORD=[HIDDEN]"
            else
                echo "  $line"
            fi
        done
    else
        log_error "✗ 未找到生产环境配置文件"
        return 1
    fi
}

# 检查docker-compose配置
check_docker_compose_config() {
    log_info "检查docker-compose配置..."
    
    if [[ -f "docker-compose.production.yml" ]]; then
        log_success "✓ 找到docker-compose生产环境配置"
        
        # 检查后端服务的环境变量配置
        if grep -A 20 "anxin-backend:" docker-compose.production.yml | grep -E "(DB_HOST|DB_NAME|DB_USER)" > /dev/null; then
            log_success "✓ 后端服务配置了数据库环境变量"
        else
            log_error "✗ 后端服务未正确配置数据库环境变量"
        fi
    else
        log_error "✗ 未找到docker-compose生产环境配置"
        return 1
    fi
}

# 检查容器环境变量
check_container_environment() {
    log_info "检查容器内环境变量..."
    
    if docker ps --filter "name=anxin-backend-prod" --format "{{.Names}}" | grep -q "anxin-backend-prod"; then
        log_success "✓ 后端容器正在运行"
        
        # 检查容器内的数据库环境变量
        echo "容器内数据库配置:"
        docker exec anxin-backend-prod env | grep -E "^(DB_HOST|DB_PORT|DB_NAME|DB_USER)=" | while read line; do
            echo "  $line"
        done
        
        # 检查密码是否设置（不显示实际值）
        if docker exec anxin-backend-prod env | grep -q "^DB_PASSWORD="; then
            log_success "✓ DB_PASSWORD 已设置"
        else
            log_error "✗ DB_PASSWORD 未设置"
        fi
    else
        log_warn "后端容器未运行，无法检查容器环境变量"
    fi
}

# 检查数据库连接
check_database_connection() {
    log_info "检查数据库连接..."
    
    # 从环境文件读取数据库配置
    if [[ -f "environments/.env.production" ]]; then
        source environments/.env.production
        
        # 检查MySQL容器是否运行
        if docker ps --filter "name=anxin-mysql-prod" --format "{{.Names}}" | grep -q "anxin-mysql-prod"; then
            log_success "✓ MySQL容器正在运行"
            
            # 测试数据库连接
            log_info "测试数据库连接..."
            if docker exec anxin-mysql-prod mysql -u"$DB_USER" -p"$DB_PASSWORD" -e "SELECT 1;" "$DB_NAME" 2>/dev/null; then
                log_success "✓ 数据库连接测试成功"
                
                # 检查数据库是否存在
                if docker exec anxin-mysql-prod mysql -u"$DB_USER" -p"$DB_PASSWORD" -e "SHOW DATABASES;" | grep -q "$DB_NAME"; then
                    log_success "✓ 数据库 $DB_NAME 存在"
                else
                    log_error "✗ 数据库 $DB_NAME 不存在"
                fi
            else
                log_error "✗ 数据库连接测试失败"
            fi
        else
            log_error "✗ MySQL容器未运行"
        fi
    else
        log_error "无法读取环境配置文件"
    fi
}

# 检查应用启动日志中的数据库连接信息
check_application_logs() {
    log_info "检查应用启动日志..."
    
    if docker ps --filter "name=anxin-backend-prod" --format "{{.Names}}" | grep -q "anxin-backend-prod"; then
        # 查看最近的启动日志
        log_info "最近的启动日志:"
        ./deploy.sh logs backend -e production --tail 30 | grep -E "(数据库|database|mysql|jdbc)" || true
        
        # 检查是否有数据库连接错误
        if ./deploy.sh logs backend -e production --tail 100 | grep -i "connection.*refused\|access.*denied\|unknown.*database"; then
            log_error "发现数据库连接错误"
        else
            log_success "✓ 未发现数据库连接错误"
        fi
    else
        log_warn "后端容器未运行，无法检查应用日志"
    fi
}

# 验证数据库表结构
verify_database_schema() {
    log_info "验证数据库表结构..."
    
    if [[ -f "environments/.env.production" ]]; then
        source environments/.env.production
        
        if docker ps --filter "name=anxin-mysql-prod" --format "{{.Names}}" | grep -q "anxin-mysql-prod"; then
            # 检查关键表是否存在
            local tables=("sys_user" "sys_role" "sys_menu" "sys_dept")
            
            for table in "${tables[@]}"; do
                if docker exec anxin-mysql-prod mysql -u"$DB_USER" -p"$DB_PASSWORD" -e "DESCRIBE $table;" "$DB_NAME" 2>/dev/null > /dev/null; then
                    log_success "✓ 表 $table 存在"
                else
                    log_error "✗ 表 $table 不存在"
                fi
            done
        fi
    fi
}

# 显示修复建议
show_fix_suggestions() {
    log_info "修复建议:"
    echo "----------------------------------------"
    echo "如果发现数据库配置问题，请检查:"
    echo ""
    echo "1. 环境变量配置 (environments/.env.production):"
    echo "   - DB_NAME 应该是 anxin_prod"
    echo "   - DB_USER 应该是 anxin_prod"
    echo "   - DB_PASSWORD 应该是正确的生产环境密码"
    echo ""
    echo "2. 重启后端服务以应用新配置:"
    echo "   ./deploy.sh restart backend -e production"
    echo ""
    echo "3. 如果数据库不存在，需要初始化:"
    echo "   ./deploy.sh exec mysql -e production"
    echo "   CREATE DATABASE anxin_prod CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
    echo ""
    echo "4. 导入数据库结构:"
    echo "   docker exec -i anxin-mysql-prod mysql -uroot -p < database/02-schema.sql"
    echo "----------------------------------------"
}

# 主函数
main() {
    log_info "数据库配置验证工具"
    echo "========================================"
    
    # 检查环境
    check_directory
    
    # 检查配置文件
    check_environment_variables
    echo ""
    
    check_docker_compose_config
    echo ""
    
    # 检查运行时配置
    check_container_environment
    echo ""
    
    # 检查数据库连接
    check_database_connection
    echo ""
    
    # 检查应用日志
    check_application_logs
    echo ""
    
    # 验证数据库结构
    verify_database_schema
    echo ""
    
    # 显示修复建议
    show_fix_suggestions
    
    echo "========================================"
    log_success "验证完成!"
}

# 如果脚本被直接执行
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi