"""
Add editor role to UserRole enum and ensure role column exists on users table
"""
from alembic import op
import sqlalchemy as sa
import enum

# revision identifiers, used by Alembic.
revision = 'add_userrole_editor_and_column'
down_revision = None  # Set this to the latest revision in your repo
branch_labels = None
depends_on = None

# Define the new enum including 'editor'
class userrole_enum(enum.Enum):
    user = "user"
    editor = "editor"
    admin = "admin"
    superadmin = "superadmin"

def upgrade():
    # MySQL: check if 'role' column exists
    conn = op.get_bind()
    insp = sa.inspect(conn)
    columns = [col['name'] for col in insp.get_columns('users')]
    if 'role' not in columns:
        with op.batch_alter_table('users') as batch_op:
            batch_op.add_column(sa.Column('role', sa.Enum('user', 'editor', 'admin', 'superadmin', name='userrole'), nullable=False, server_default='user'))
    else:
        # If the column exists, alter the ENUM to add 'editor' if not present
        # MySQL: ALTER TABLE users MODIFY COLUMN role ENUM(...)
        conn.execute(sa.text(
            "ALTER TABLE users MODIFY COLUMN role ENUM('user','editor','admin','superadmin') NOT NULL DEFAULT 'user'"
        ))

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('users') as batch_op:
        batch_op.drop_column('role')
    # ### end Alembic commands ###
