"""add preferred_view to user

Revision ID: b978642e7b10
Revises: 26b0e5357f52
Create Date: 2025-05-24 08:36:03.426879

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


# revision identifiers, used by Alembic.
revision = 'b978642e7b10'
down_revision = '26b0e5357f52'
branch_labels = None
depends_on = None


def upgrade():
    # Check if the column exists before adding it
    conn = op.get_bind()
    inspector = inspect(conn)
    columns = [col['name'] for col in inspector.get_columns('user')]
    
    if 'preferred_view' not in columns:
        # Add preferred_view as nullable first
        with op.batch_alter_table('user', schema=None) as batch_op:
            batch_op.add_column(sa.Column('preferred_view', sa.String(length=10), nullable=True))
        # Set default value for existing users
        op.execute("UPDATE \"user\" SET preferred_view = 'grid'")
        # Make the column non-nullable
        with op.batch_alter_table('user', schema=None) as batch_op:
            batch_op.alter_column('preferred_view', nullable=False)


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.drop_column('preferred_view')

    with op.batch_alter_table('room_member_permissions', schema=None) as batch_op:
        batch_op.add_column(sa.Column('preferred_view', sa.VARCHAR(length=10), autoincrement=False, nullable=False))

    # ### end Alembic commands ###
