"""Add table_name column to LastRefreshDB

Revision ID: 711feaa741bb
Revises: 9783bd3941f1
Create Date: 2025-08-05 11:59:56.440867

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '711feaa741bb'
down_revision = '9783bd3941f1'
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # For SQLite, we need to do a table recreation approach since it doesn't support ALTER COLUMN
    
    # Step 1: Create a new table with the updated schema
    op.create_table('last_refresh_new',
        sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
        sa.Column('table_name', sa.String(), nullable=False),
        sa.Column('source_last_updated', sa.DateTime(), nullable=False),
        sa.Column('db_last_updated', sa.DateTime(), nullable=False),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index('ix_last_refresh_table_name', 'last_refresh_new', ['table_name'], unique=False)
    
    # Step 2: Copy existing data with default table_name
    op.execute("""
        INSERT INTO last_refresh_new (id, table_name, source_last_updated, db_last_updated)
        SELECT id, 'file_share_paths', source_last_updated, db_last_updated
        FROM last_refresh
    """)
    
    # Step 3: Drop the old table
    op.drop_table('last_refresh')
    
    # Step 4: Rename the new table
    op.rename_table('last_refresh_new', 'last_refresh')
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # Create the old table structure
    op.create_table('last_refresh_old',
        sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
        sa.Column('source_last_updated', sa.DateTime(), nullable=False),
        sa.Column('db_last_updated', sa.DateTime(), nullable=False),
        sa.PrimaryKeyConstraint('id')
    )
    
    # Copy data back without table_name column
    op.execute("""
        INSERT INTO last_refresh_old (id, source_last_updated, db_last_updated)
        SELECT id, source_last_updated, db_last_updated
        FROM last_refresh
    """)
    
    # Drop the current table and rename
    op.drop_index('ix_last_refresh_table_name', table_name='last_refresh')
    op.drop_table('last_refresh')
    op.rename_table('last_refresh_old', 'last_refresh')
    # ### end Alembic commands ###