"""Add user ban fields (ban_reason, ban_at)

Revision ID: 027
Revises: 026
Create Date: 2026-07-05

补录用户封禁字段。生产数据库已手动添加过这些字段，
因此 upgrade 做幂等检查。
"""

import sqlalchemy as sa

from alembic import context, op

revision = "027"
down_revision = "026"
branch_labels = None
depends_on = None


def _column_exists(table: str, column: str) -> bool:
    if context.is_offline_mode():
        return False
    conn = op.get_bind()
    result = conn.execute(
        sa.text(
            "SELECT COUNT(*) FROM information_schema.columns " "WHERE table_name = :table AND column_name = :column"
        ),
        {"table": table, "column": column},
    )
    return result.scalar() > 0


def upgrade() -> None:
    if not _column_exists("users", "ban_reason"):
        op.add_column("users", sa.Column("ban_reason", sa.Text(), nullable=True))

    if not _column_exists("users", "ban_at"):
        op.add_column("users", sa.Column("ban_at", sa.DateTime(), nullable=True))


def downgrade() -> None:
    op.drop_column("users", "ban_at")
    op.drop_column("users", "ban_reason")
