"""add Environment creator_role

Revision ID: cfab6c8243cb
Revises: 502e79c55d2d
Create Date: 2019-09-10 11:21:43.252592

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

# revision identifiers, used by Alembic.
revision = "cfab6c8243cb"  # pragma: allowlist secret
down_revision = "f03333c42bdb"  # pragma: allowlist secret
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "environments",
        sa.Column("creator_id", postgresql.UUID(as_uuid=True), nullable=True),
    )
    op.create_foreign_key(
        "fk_users_id", "environments", "users", ["creator_id"], ["id"]
    )
    # ### end Alembic commands ###

    # Default environment's creator id to the portfolio POC
    conn = op.get_bind()
    results = conn.execute(
        """
        SELECT
            DISTINCT ON (e.id) e.id as id, pr.user_id as user_id
        FROM environments e
            JOIN applications a ON e.application_id = a.id
            JOIN portfolios p ON a.portfolio_id = p.id
            JOIN portfolio_roles pr ON pr.portfolio_id = p.id
            JOIN portfolio_roles_permission_sets prps ON prps.portfolio_role_id = pr.id
            JOIN permission_sets ps ON prps.permission_set_id = ps.id
        WHERE ps.name = 'portfolio_poc'
        ORDER BY e.id;
        """
    ).fetchall()

    for r in results:
        conn.execute(
            "UPDATE environments e SET creator_id = %s WHERE e.id = %s",
            [r["user_id"], r["id"]],
        )

    op.alter_column("environments", "creator_id", nullable=False)


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint("fk_users_id", "environments", type_="foreignkey")
    op.drop_column("environments", "creator_id")
    # ### end Alembic commands ###
