#!/bin/bash
# verify-migration-rollback.sh - 验证迁移回滚
# 依赖: grep
# 用法: ./verify-migration-rollback.sh <migration-file>

set -e

MIGRATION_FILE=$1

if [ -z "$MIGRATION_FILE" ]; then
    echo "用法: $0 <migration-file>"
    exit 1
fi

echo "=== 迁移回滚验证 ==="
echo "迁移文件: ${MIGRATION_FILE}"
echo ""

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

pass() { echo -e "${GREEN}[PASS]${NC} $1"; }
fail() { echo -e "${RED}[FAIL]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }

# 检查文件是否存在
if [ ! -f "$MIGRATION_FILE" ]; then
    fail "迁移文件不存在: $MIGRATION_FILE"
    exit 1
fi

# 检查是否包含 UP 和 DOWN
if grep -q "UP" "$MIGRATION_FILE"; then
    pass "包含 UP 脚本"
else
    fail "缺少 UP 脚本"
fi

if grep -q "DOWN" "$MIGRATION_FILE"; then
    pass "包含 DOWN 脚本"
else
    fail "缺少 DOWN 脚本"
fi

# 检查 DOWN 脚本是否被注释
if grep -E "^--.*DROP|^--.*DELETE|^--.*ALTER.*DROP" "$MIGRATION_FILE" > /dev/null; then
    warn "DOWN 脚本被注释，请取消注释后测试回滚"
fi

# 检查是否有危险操作
if grep -i "DROP TABLE\|TRUNCATE\|DELETE FROM" "$MIGRATION_FILE" | grep -v "^--" > /dev/null; then
    warn "包含危险操作（DROP/TRUNCATE/DELETE），请确保已备份"
fi

# 检查命名规范
FILENAME=$(basename "$MIGRATION_FILE")
if echo "$FILENAME" | grep -qE "^[0-9]{14}_[a-z_]+\.sql$"; then
    pass "文件名符合规范"
else
    warn "文件名不符合规范: YYYYMMDDHHMMSS_description.sql"
fi

echo ""
echo "=== 验证完成 ==="
