#!/bin/bash
#
# 检查所有微服务的数据库和数据表
#

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="$SCRIPT_DIR/../.env"

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

# Load environment variables
if [ -f "$ENV_FILE" ]; then
    source "$ENV_FILE"
fi

POSTGRES_USER="${POSTGRES_USER:-rwa_user}"
POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-rwa_secure_password}"

# 服务与数据库映射
declare -A SERVICES=(
    ["identity-service"]="rwa_identity"
    ["wallet-service"]="rwa_wallet"
    ["backup-service"]="rwa_backup"
    ["planting-service"]="rwa_planting"
    ["referral-service"]="rwa_referral"
    ["reward-service"]="rwa_reward"
    ["mpc-service"]="rwa_mpc"
    ["leaderboard-service"]="rwa_leaderboard"
    ["reporting-service"]="rwa_reporting"
    ["authorization-service"]="rwa_authorization"
    ["admin-service"]="rwa_admin"
    ["presence-service"]="rwa_presence"
)

echo "============================================"
echo "RWA 微服务数据库检查"
echo "============================================"
echo ""

total=0
success=0
failed=0

for service in "${!SERVICES[@]}"; do
    db="${SERVICES[$service]}"
    total=$((total + 1))

    echo -n "检查 $service ($db): "

    # 检查数据库是否存在
    db_exists=$(docker exec rwa-postgres psql -U "$POSTGRES_USER" -tAc "SELECT 1 FROM pg_database WHERE datname='$db'" 2>/dev/null || echo "")

    if [ "$db_exists" != "1" ]; then
        echo -e "${RED}数据库不存在${NC}"
        failed=$((failed + 1))
        continue
    fi

    # 获取表数量
    table_count=$(docker exec rwa-postgres psql -U "$POSTGRES_USER" -d "$db" -tAc "SELECT count(*) FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'" 2>/dev/null || echo "0")

    if [ "$table_count" -eq 0 ]; then
        echo -e "${YELLOW}数据库存在，但无表${NC}"
        failed=$((failed + 1))
    else
        echo -e "${GREEN}OK${NC} ($table_count 张表)"
        success=$((success + 1))

        # 显示表列表
        tables=$(docker exec rwa-postgres psql -U "$POSTGRES_USER" -d "$db" -tAc "SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE' ORDER BY table_name" 2>/dev/null || echo "")
        if [ -n "$tables" ]; then
            echo "$tables" | while read -r table; do
                if [ -n "$table" ]; then
                    echo "    - $table"
                fi
            done
        fi
    fi
    echo ""
done

echo "============================================"
echo "总结: $success/$total 个服务数据库正常"
if [ $failed -gt 0 ]; then
    echo -e "${RED}$failed 个服务存在问题${NC}"
    exit 1
else
    echo -e "${GREEN}所有服务数据库正常${NC}"
fi
