#!/bin/bash
# 验证数据库 Schema 完整性
# 依赖: psql (PostgreSQL) 或 mysql client
# 用法: ./verify-schema.sh

set -e

DB_TYPE="${DB_TYPE:-postgres}"
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_NAME="${DB_NAME:-rmdc}"
DB_USER="${DB_USER:-rmdc}"
DB_PASSWORD="${DB_PASSWORD:-}"

echo "=== 验证工单模块 Schema ==="
echo "数据库: $DB_TYPE://$DB_HOST:$DB_PORT/$DB_NAME"
echo ""

# 必需的表
REQUIRED_TABLES=(
    "workflows"
    "workflow_steps"
    "workflow_track_history"
    "user_registration_ext"
    "user_management_ext"
    "project_detail_ext"
    "microservice_update_ext"
)

# workflows 表必需的列
WORKFLOWS_COLUMNS=(
    "id"
    "version"
    "module_code"
    "workflow_type"
    "status"
    "creator_id"
    "assignee_id"
    "created_at"
    "updated_at"
)

FAILED=0
PASSED=0

# 检查表是否存在
check_table_exists() {
    local table=$1
    if [ "$DB_TYPE" == "postgres" ]; then
        result=$(PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -t -c \
            "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = '$table')" 2>/dev/null | tr -d ' ')
        [ "$result" == "t" ] && return 0 || return 1
    else
        result=$(mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" -D "$DB_NAME" -N -e \
            "SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '$table'" 2>/dev/null)
        [ "$result" -gt 0 ] && return 0 || return 1
    fi
}

# 检查列是否存在
check_column_exists() {
    local table=$1
    local column=$2
    if [ "$DB_TYPE" == "postgres" ]; then
        result=$(PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -t -c \
            "SELECT EXISTS (SELECT FROM information_schema.columns WHERE table_name = '$table' AND column_name = '$column')" 2>/dev/null | tr -d ' ')
        [ "$result" == "t" ] && return 0 || return 1
    else
        result=$(mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" -D "$DB_NAME" -N -e \
            "SELECT COUNT(*) FROM information_schema.columns WHERE table_name = '$table' AND column_name = '$column'" 2>/dev/null)
        [ "$result" -gt 0 ] && return 0 || return 1
    fi
}

echo "--- 检查表是否存在 ---"
for table in "${REQUIRED_TABLES[@]}"; do
    if check_table_exists "$table"; then
        echo "[PASS] 表 $table 存在"
        ((PASSED++))
    else
        echo "[FAIL] 表 $table 不存在"
        ((FAILED++))
    fi
done

echo ""
echo "--- 检查 workflows 表核心字段 ---"
for column in "${WORKFLOWS_COLUMNS[@]}"; do
    if check_column_exists "workflows" "$column"; then
        echo "[PASS] workflows.$column 字段存在"
        ((PASSED++))
    else
        echo "[FAIL] workflows.$column 字段缺失"
        ((FAILED++))
    fi
done

echo ""
echo "--- 检查乐观锁字段 ---"
if check_column_exists "workflows" "version"; then
    echo "[PASS] workflows.version 字段存在（乐观锁）"
    ((PASSED++))
else
    echo "[FAIL] workflows.version 字段缺失（乐观锁必需）"
    ((FAILED++))
fi

echo ""
echo "--- 检查外键约束 ---"
EXT_TABLES=("user_registration_ext" "user_management_ext" "project_detail_ext" "microservice_update_ext")
for table in "${EXT_TABLES[@]}"; do
    if check_column_exists "$table" "workflow_id"; then
        echo "[PASS] $table.workflow_id 字段存在"
        ((PASSED++))
    else
        echo "[FAIL] $table.workflow_id 字段缺失"
        ((FAILED++))
    fi
done

echo ""
echo "=== 验证结果 ==="
echo "通过: $PASSED"
echo "失败: $FAILED"

if [ $FAILED -gt 0 ]; then
    echo ""
    echo "请运行数据库迁移修复缺失的表/字段"
    exit 1
else
    echo ""
    echo "所有 Schema 检查通过！"
    exit 0
fi
