"""focus_solo_orgs

Revision: 0211
Revision ID: f9c853eb5e2c
Revises: ee6fba69aef3
Create Date: 2021-05-24 16:27:45.280261

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


# revision identifiers, used by Alembic.
revision = 'f9c853eb5e2c'
down_revision = 'ee6fba69aef3'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("""
        WITH users_with_single_org AS (
            SELECT u.id user_id, om.org_id
            FROM users u JOIN organization_members om ON om.user_id = u.id
            WHERE (SELECT count(*) FROM organization_members WHERE user_id = u.id) = 1 AND om.permission > 0
            AND (u.user_org_id IS NULL OR (SELECT count(*) FROM projects WHERE owner_id = u.user_org_id) = 0)
        )
        UPDATE users
        SET app_params = (app_params::jsonb || jsonb_build_object('appContextFocus', ('["org", ' || users_with_single_org.org_id || ']')::json))::json
        FROM users_with_single_org
        WHERE users_with_single_org.user_id = users.id
    """)

    op.execute("""
        WITH users_with_single_org AS (
            SELECT u.id user_id, om.org_id
            FROM users u JOIN organization_members om ON om.user_id = u.id
            WHERE (SELECT count(*) FROM organization_members WHERE user_id = u.id) = 1 AND om.permission > 0
            AND (u.user_org_id IS NULL OR (SELECT count(*) FROM projects WHERE owner_id = u.user_org_id) = 0)
        )
        UPDATE views
        SET org_id = users_with_single_org.org_id
        FROM users_with_single_org
        WHERE views.user_id = users_with_single_org.user_id AND views.project_id IS NULL
    """)


def downgrade():
    pass
