"""add assignee

Revision ID: e1c315078dc3
Revises: 04115bd903c0
Create Date: 2019-03-30 17:48:04.431648

"""
from alembic import op
import sqlalchemy as sa
from pabu.tools import get_table

# revision identifiers, used by Alembic.
revision = 'e1c315078dc3'
down_revision = '04115bd903c0'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('issues', sa.Column('assignee_id', sa.Integer(), nullable=True))
    op.add_column('issues', sa.Column('reporter_id', sa.Integer(), nullable=True))
    op.drop_constraint('issues_user_id_fkey', 'issues', type_='foreignkey')
    op.create_foreign_key(None, 'issues', 'users', ['assignee_id'], ['id'], ondelete='SET NULL')
    op.create_foreign_key(None, 'issues', 'users', ['reporter_id'], ['id'], ondelete='CASCADE')

    issues = get_table(op.get_bind(), 'issues')
    op.execute(issues.update().values(reporter_id = issues.c.user_id))
    op.execute(issues.update().values(assignee_id = issues.c.user_id).where(issues.c.status.in_(['done', 'in progress'])))

    op.alter_column('issues', 'reporter_id', nullable=False)
    op.drop_column('issues', 'user_id')
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('issues', sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True))
    op.drop_constraint(None, 'issues', type_='foreignkey')
    op.drop_constraint(None, 'issues', type_='foreignkey')
    op.create_foreign_key('issues_user_id_fkey', 'issues', 'users', ['user_id'], ['id'], ondelete='CASCADE')

    issues = get_table(op.get_bind(), 'issues')
    op.execute(issues.update().values(user_id = issues.c.reporter_id))

    op.drop_column('issues', 'reporter_id')
    op.drop_column('issues', 'assignee_id')
    op.alter_column('issues', 'user_id', nullable=False)
    # ### end Alembic commands ###
