"""Add starred column to room_file table

Revision ID: 6651332488d9
Revises: be1f7bdd10e1
Create Date: 2025-05-24 18:14:38.320999

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = '6651332488d9'
down_revision = 'be1f7bdd10e1'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    inspector = inspect(conn)
    columns = [col['name'] for col in inspector.get_columns('room_file')]
    
    with op.batch_alter_table('room_file', schema=None) as batch_op:
        if 'starred' not in columns:
            batch_op.add_column(sa.Column('starred', sa.Boolean(), nullable=True))
        
        # Only alter columns if they exist
        if 'path' in columns:
            batch_op.alter_column('path',
                   existing_type=sa.VARCHAR(length=1024),
                   type_=sa.String(length=255),
                   existing_nullable=False)
        if 'size' in columns:
            batch_op.alter_column('size',
                   existing_type=sa.BIGINT(),
                   type_=sa.Integer(),
                   existing_nullable=True)
        if 'uploaded_by' in columns:
            batch_op.alter_column('uploaded_by',
                   existing_type=sa.INTEGER(),
                   nullable=True)
        if 'uploaded_at' in columns:
            batch_op.alter_column('uploaded_at',
                   existing_type=postgresql.TIMESTAMP(),
                   nullable=True)

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    inspector = inspect(conn)
    columns = [col['name'] for col in inspector.get_columns('room_file')]
    
    with op.batch_alter_table('room_file', schema=None) as batch_op:
        if 'uploaded_at' in columns:
            batch_op.alter_column('uploaded_at',
                   existing_type=postgresql.TIMESTAMP(),
                   nullable=False)
        if 'uploaded_by' in columns:
            batch_op.alter_column('uploaded_by',
                   existing_type=sa.INTEGER(),
                   nullable=False)
        if 'size' in columns:
            batch_op.alter_column('size',
                   existing_type=sa.Integer(),
                   type_=sa.BIGINT(),
                   existing_nullable=True)
        if 'path' in columns:
            batch_op.alter_column('path',
                   existing_type=sa.String(length=255),
                   type_=sa.VARCHAR(length=1024),
                   existing_nullable=False)
        if 'starred' in columns:
            batch_op.drop_column('starred')

    # ### end Alembic commands ###
