"""add_automation_role_member

Revision: 0233
Revision ID: 437b60ce2a7c
Revises: 658071592313
Create Date: 2022-03-21 08:06:46.042030

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


# revision identifiers, used by Alembic.
revision = '437b60ce2a7c'
down_revision = '658071592313'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("""
        INSERT INTO role_permissions (role_id, object_type, actions)
        SELECT roles.id, 'project', '{"RUN_AUTO_ACTIONS"}'::varchar[]
        FROM roles WHERE roles.builtin = 'MEMBER'
    """)

    op.execute("""
        UPDATE roles SET cache_id = uuid_generate_v4()
        WHERE roles.id IN (
            SELECT DISTINCT roles.id
            FROM roles, role_permissions
            WHERE role_permissions.role_id = roles.id
            AND roles.builtin in ('ADMIN', 'MEMBER')
            AND role_permissions.object_type = 'project'
            AND role_permissions.object_id IS NULL
            AND (role_permissions.actions @> '{"RUN_AUTO_ACTIONS"}'::varchar[])
        )
    """)

    op.execute("""
        UPDATE projects SET members_cache_id = uuid_generate_v4() FROM organizations, roles, role_permissions
        WHERE organizations.id = projects.owner_id
            AND roles.owner_id = organizations.id
            AND roles.builtin in ('ADMIN', 'MEMBER')
            AND role_permissions.role_id = roles.id
            AND role_permissions.object_type = 'project'
            AND role_permissions.object_id IS NULL
            AND (role_permissions.actions @> '{"RUN_AUTO_ACTIONS"}'::varchar[])
    """)


def downgrade():
    pass
