#!/bin/bash
#
# 运行所有测试
#

set -e

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

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

echo "========================================"
echo -e "${BLUE}VBase 集成测试套件${NC}"
echo "========================================"
echo ""

# 生成统一的时间戳（所有测试使用相同时间戳，避免冲突）
export TEST_TIMESTAMP=$(date +%s)
echo "测试时间戳: $TEST_TIMESTAMP"
echo ""

# 测试脚本列表
TESTS=(
    "00_none_auth.sh:未登录访问测试"
    "01_setup_users.sh:用户初始化与基础认证测试"
    "02_resource_perm.sh:资源权限交叉验证测试"
    "03_org_permission.sh:组织权限测试"
    "04_org_load_middleware.sh:LoadOrg 中间件测试"
)

PASSED=0
FAILED=0

# 运行每个测试
for test_info in "${TESTS[@]}"; do
    script="${test_info%%:*}"
    name="${test_info##*:}"

    echo ""
    echo "========================================"
    echo -e "${YELLOW}运行: $name${NC}"
    echo "========================================"

    if bash "$script"; then
        echo -e "${GREEN}✓ $name 通过${NC}"
        ((PASSED++))
    else
        echo -e "${RED}✗ $name 失败${NC}"
        ((FAILED++))
        echo ""
        echo -e "${RED}测试中止${NC}"
        break
    fi
done

# 测试摘要
echo ""
echo "========================================"
echo -e "${BLUE}测试摘要${NC}"
echo "========================================"
echo -e "通过: ${GREEN}$PASSED${NC}"
echo -e "失败: ${RED}$FAILED${NC}"
echo "总计: ${#TESTS[@]}"

if [ $FAILED -eq 0 ]; then
    echo ""
    echo -e "${GREEN}所有测试通过!${NC}"
    exit 0
else
    echo ""
    echo -e "${RED}存在失败的测试${NC}"
    exit 1
fi
