"""Create user_starred_file table and remove starred column

Revision ID: create_user_starred_file_table
Revises: 6651332488d9
Create Date: 2024-03-19 10:00:00.000000

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

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

def upgrade():
    # Create user_starred_file table
    conn = op.get_bind()
    inspector = inspect(conn)
    tables = inspector.get_table_names()
    
    if 'user_starred_file' not in tables:
        op.create_table('user_starred_file',
            sa.Column('id', sa.Integer(), nullable=False),
            sa.Column('user_id', sa.Integer(), nullable=False),
            sa.Column('file_id', sa.Integer(), nullable=False),
            sa.Column('starred_at', sa.DateTime(), nullable=True),
            sa.ForeignKeyConstraint(['file_id'], ['room_file.id'], ),
            sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
            sa.PrimaryKeyConstraint('id'),
            sa.UniqueConstraint('user_id', 'file_id', name='unique_user_file_star')
        )
    
    # Remove starred column from room_file
    with op.batch_alter_table('room_file', schema=None) as batch_op:
        batch_op.drop_column('starred')

def downgrade():
    # Add starred column back to room_file
    with op.batch_alter_table('room_file', schema=None) as batch_op:
        batch_op.add_column(sa.Column('starred', sa.Boolean(), nullable=True))
    
    # Drop user_starred_file table
    op.drop_table('user_starred_file') 