"""Add user banned fields

Revision ID: 012_add_user_banned
Revises: 011_add_challenge_proposals
Create Date: 2024-12-18

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect


# revision identifiers, used by Alembic.
revision: str = '012_add_user_banned'
down_revision: Union[str, None] = '011_add_challenge_proposals'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def column_exists(table_name: str, column_name: str) -> bool:
    bind = op.get_bind()
    inspector = inspect(bind)
    columns = [col['name'] for col in inspector.get_columns(table_name)]
    return column_name in columns


def upgrade() -> None:
    if not column_exists('users', 'is_banned'):
        op.add_column('users', sa.Column('is_banned', sa.Boolean(), server_default='false', nullable=False))
    if not column_exists('users', 'banned_at'):
        op.add_column('users', sa.Column('banned_at', sa.DateTime(), nullable=True))
    if not column_exists('users', 'banned_by_id'):
        op.add_column('users', sa.Column('banned_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True))
    if not column_exists('users', 'ban_reason'):
        op.add_column('users', sa.Column('ban_reason', sa.String(500), nullable=True))


def downgrade() -> None:
    if column_exists('users', 'ban_reason'):
        op.drop_column('users', 'ban_reason')
    if column_exists('users', 'banned_by_id'):
        op.drop_column('users', 'banned_by_id')
    if column_exists('users', 'banned_at'):
        op.drop_column('users', 'banned_at')
    if column_exists('users', 'is_banned'):
        op.drop_column('users', 'is_banned')
