"""remove_org_focus

Revision: 0238
Revision ID: f9352a1f06eb
Revises: f026609b2ae2
Create Date: 2022-03-08 11:58:54.082504

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


# revision identifiers, used by Alembic.
revision = 'f9352a1f06eb'
down_revision = 'f026609b2ae2'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("""
        UPDATE views SET org_id = null WHERE user_id IS NOT NULL AND project_id IS NULL
    """)

    op.execute("""
        UPDATE users SET app_params = jsonb_set(app_params::jsonb, '{hiddenOrgs}',
            (SELECT jsonb_agg(org_id) FROM organization_members WHERE user_id = users.id AND permission > 0 AND org_id != (app_params->'appContextFocus'->>1)::integer))
        WHERE app_params->'appContextFocus'->>0 = 'org'
    """)

    op.execute("""
        UPDATE users SET app_params = jsonb_set(app_params::jsonb, '{home}', concat('"org:', organizations.slug, '"')::jsonb)
        FROM organizations
        WHERE app_params->'appContextFocus'->>0 = 'org' AND organizations.id = (app_params->'appContextFocus'->>1)::integer
    """)

    op.execute("""
        UPDATE users SET app_params = jsonb_set(app_params::jsonb, '{home}', '"inbox"'::jsonb)
        WHERE app_params->>'inboxAsHome' = 'true'
    """)

    op.execute("""
        UPDATE users SET app_params = jsonb_strip_nulls(jsonb_set(jsonb_set(jsonb_set(jsonb_set(
            app_params::jsonb,
            '{inboxAsHome}', 'null'::jsonb),
            '{last_whatsnew_id_read}', 'null'::jsonb),
            '{last_whatsnew_id_closed}', 'null'::jsonb),
            '{appContextFocus}', 'null'::jsonb)
        )::json
    """)


def downgrade():
    pass
