"""
添加邮箱验证相关字段的数据库迁移脚本
运行方式: python migrate_email_verification.py
"""

from app import create_app
from models import db

def migrate():
    """执行数据库迁移"""
    app = create_app()

    with app.app_context():
        try:
            # 添加邮箱验证相关字段
            with db.engine.connect() as conn:
                # 检查字段是否已存在
                result = conn.execute(db.text("""
                    SELECT COUNT(*) as count
                    FROM information_schema.columns
                    WHERE table_name='users' AND column_name='email_verified'
                """))
                exists = result.fetchone()[0] > 0

                if not exists:
                    print("开始添加邮箱验证字段...")

                    # 添加 email_verified 字段
                    conn.execute(db.text("""
                        ALTER TABLE users
                        ADD COLUMN email_verified BOOLEAN DEFAULT FALSE COMMENT '邮箱是否已验证'
                    """))
                    conn.commit()
                    print("[OK] 添加 email_verified 字段")

                    # 添加 email_verified_at 字段
                    conn.execute(db.text("""
                        ALTER TABLE users
                        ADD COLUMN email_verified_at DATETIME COMMENT '邮箱验证时间'
                    """))
                    conn.commit()
                    print("[OK] 添加 email_verified_at 字段")

                    # 添加 email_verify_token 字段
                    conn.execute(db.text("""
                        ALTER TABLE users
                        ADD COLUMN email_verify_token VARCHAR(100) COMMENT '邮箱验证令牌'
                    """))
                    conn.commit()
                    print("[OK] 添加 email_verify_token 字段")

                    # 添加 email_verify_token_expires 字段
                    conn.execute(db.text("""
                        ALTER TABLE users
                        ADD COLUMN email_verify_token_expires DATETIME COMMENT '验证令牌过期时间'
                    """))
                    conn.commit()
                    print("[OK] 添加 email_verify_token_expires 字段")

                    print("\n[SUCCESS] 邮箱验证字段迁移完成！")
                else:
                    print("[SKIP] 邮箱验证字段已存在，跳过迁移")

        except Exception as e:
            print(f"[ERROR] 迁移失败: {str(e)}")
            raise

if __name__ == '__main__':
    migrate()
