"""Add challenge proposals support

Revision ID: 011_add_challenge_proposals
Revises: 010_add_telegram_profile
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 = '011_add_challenge_proposals'
down_revision: Union[str, None] = '010_add_telegram_profile'
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('challenges', 'proposed_by_id'):
        op.add_column('challenges', sa.Column('proposed_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True))
    if not column_exists('challenges', 'status'):
        op.add_column('challenges', sa.Column('status', sa.String(20), server_default='approved', nullable=False))


def downgrade() -> None:
    if column_exists('challenges', 'status'):
        op.drop_column('challenges', 'status')
    if column_exists('challenges', 'proposed_by_id'):
        op.drop_column('challenges', 'proposed_by_id')
