"""update_workflow_modules

Revision ID: fa12b8322112
Revises: 077b7c925ded
Create Date: 2021-03-12 20:42:03.286727+00:00

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

# revision identifiers, used by Alembic.
revision = 'fa12b8322112'
down_revision = '077b7c925ded'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - but checked! ###
    op.add_column('action', sa.Column('description', sa.String(), nullable=True, default=""))
    op.execute("UPDATE action SET description = ''")
    op.alter_column('action', 'description', nullable=False)
    op.drop_constraint('condition_rule_id_fkey', 'condition', type_='foreignkey')
    op.create_foreign_key('condition_rule_id_fkey', 'condition', 'rule', ['rule_id'], ['id'], ondelete='CASCADE')
    op.add_column('rule', sa.Column('description', sa.String(), nullable=True, default=""))
    op.execute("UPDATE rule SET description = ''")
    op.alter_column('rule', 'description', nullable=False)
    op.drop_column('rule', 'object')
    op.add_column('rule', sa.Column('name', sa.String()))
    op.create_unique_constraint('ux_rule_name', 'rule', ['name'])

    # Data migration: takes a few steps...
    # Model table
    t_rule = sa.Table(
        'rule',
        sa.MetaData(),
        sa.Column('description', sa.String),
        sa.Column('id', sa.Integer),
        sa.Column('model', sa.String),
        sa.Column('object_parent', sa.String),
        sa.Column('fields', sa.JSON),
        sa.Column('enabled', sa.Boolean),
        sa.Column('workspace_id', sa.Integer,),
        sa.Column('name', sa.String)
    )
    connection = op.get_bind()
    # We need id and model
    results = connection.execute(sa.select([
        t_rule.c.id,
        t_rule.c.model,
    ])).fetchall()
    # Iterate over all selected data tuples.
    for id_, model in results:
        # Update the new columns.
        connection.execute(t_rule.update().where(t_rule.c.id == id_).values(
            name=f'Rule for model {model}, {id_}',
        ))
    op.alter_column('rule', 'name', nullable=False)


def downgrade():
    # ### commands auto generated by Alembic - but checked! ###
    op.drop_constraint('ux_rule_name', 'rule', type_='unique')
    op.drop_column('rule', 'name')
    op.add_column('rule', sa.Column('object', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False))
    op.execute("UPDATE rule SET object = to_json(''::text)")
    op.alter_column('rule', 'object', nullable=False)
    op.drop_column('rule', 'description')
    op.drop_constraint('condition_rule_id_fkey', 'condition', type_='foreignkey')
    op.create_foreign_key('condition_rule_id_fkey', 'condition', 'rule', ['rule_id'], ['id'])
    op.drop_column('action', 'description')
    # ### end Alembic commands ###
