"""remove_observers_from_orgs

Revision: 0225
Revision ID: f04a85eeb070
Revises: 58cf93323b46
Create Date: 2021-09-23 19:08:42.479572

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


# revision identifiers, used by Alembic.
revision = 'f04a85eeb070'
down_revision = '58cf93323b46'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("""
        WITH orgs AS (
            SELECT DISTINCT om.org_id
            FROM organization_members om
            JOIN users u ON om.user_id = u.id
            WHERE u.is_observer IS TRUE
        )
        UPDATE organizations
        SET cache_id = uuid_generate_v4()
        FROM orgs
        WHERE id = orgs.org_id
    """)
    op.execute("""
        DELETE
        FROM organization_members om
        USING users u
        WHERE om.user_id = u.id
        AND u.is_observer IS TRUE
    """)
    op.execute("""
        UPDATE users
        SET perm_cache_id = uuid_generate_v4()
        WHERE is_observer IS TRUE
    """)


def downgrade():
    pass
