#!/usr/bin/env bash
# 断言迁移测试不可跳过
# 在CI环境中，PermissionCanonicalMigrationTest 和 AuditLogImmutabilityIntegrationTest 的 Skipped 必须为0
# 否则表示迁移验证未被执行，质量门禁失败

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
REPORT_DIR="${ROOT_DIR}/target/surefire-reports"

# 关键测试类列表（strict模式下不可跳过）
CRITICAL_TESTS=(
    "com.mosquito.project.permission.PermissionCanonicalMigrationTest"
    "com.mosquito.project.integration.AuditLogImmutabilityIntegrationTest"
    "com.mosquito.project.RolePermissionMigrationTest"
    "com.mosquito.project.FlywayMigrationSmokeTest"
)

echo "===== 关键测试跳过断言 ====="

# 检查测试报告目录是否存在
if [[ ! -d "${REPORT_DIR}" ]]; then
    echo "ERROR: 测试报告目录不存在: ${REPORT_DIR}"
    echo "请先运行 Maven 测试"
    exit 1
fi

FAILED=0

for TEST_CLASS in "${CRITICAL_TESTS[@]}"; do
    echo ""
    echo "检查: ${TEST_CLASS}"

    # 查找对应的测试报告文件
    REPORT_FILE=""
    for ext in txt xml; do
        candidate="${REPORT_DIR}/${TEST_CLASS}.${ext}"
        if [[ -f "${candidate}" ]]; then
            REPORT_FILE="${candidate}"
            break
        fi
    done

    if [[ -z "${REPORT_FILE}" ]]; then
        echo "  ERROR: 未找到测试报告文件: ${TEST_CLASS}.{txt,xml}"
        echo "  目录内容:"
        ls -la "${REPORT_DIR}" | head -20 || true
        FAILED=1
        continue
    fi

    echo "  报告: ${REPORT_FILE}"

    # 从XML报告中提取Skipped数量（如果存在）
    if [[ "${REPORT_FILE}" == *.xml ]]; then
        if grep -q 'failures="[^"]*" errors="[^"]*" skipped="[^"]*"' "${REPORT_FILE}"; then
            SKIPPED=$(grep -oP 'skipped="\K[0-9]+' "${REPORT_FILE}" | head -1)
            if [[ "${SKIPPED}" -gt 0 ]]; then
                echo "  ERROR: ${TEST_CLASS} 有 ${SKIPPED} 个被跳过！"
                echo "  在CI严格模式下，关键测试必须执行。"
                echo "  质量门禁失败：Skipped 数量必须为0"
                FAILED=1
            else
                echo "  PASS: ${TEST_CLASS} 跳过数量为0（${SKIPPED}）"
            fi
        else
            # 如果XML中没有skipped属性，检查是否完全跳过了测试
            if grep -q 'tests="0"' "${REPORT_FILE}"; then
                echo "  ERROR: ${TEST_CLASS} 未被执行（tests=\"0\"）"
                FAILED=1
            else
                echo "  INFO: 无法从XML中解析skipped数量，假设通过"
            fi
        fi
    elif [[ "${REPORT_FILE}" == *.txt ]]; then
        # 从文本报告中提取信息
        if grep -q "Skipped" "${REPORT_FILE}"; then
            # 检查是否有跳过的测试
            if grep "Skipped.*[1-9]" "${REPORT_FILE}"; then
                echo "  ERROR: ${TEST_CLASS} 有跳过的用例！"
                FAILED=1
            fi
        fi
        echo "  INFO: 文本报告格式，跳过详细检查"
    fi
done

echo ""
if [[ "${FAILED}" -eq 1 ]]; then
    echo "===== 关键测试跳过断言失败 ====="
    exit 1
fi

echo "===== 关键测试跳过断言通过 ====="
exit 0