"""sso

Revision: 0200
Revision ID: 38e954f8faf0
Revises: 259d870ba064
Create Date: 2020-12-01 15:04:11.322598

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


# revision identifiers, used by Alembic.
revision = '38e954f8faf0'
down_revision = '259d870ba064'
branch_labels = None
depends_on = None


def upgrade():
    op.create_table('organization_sso_config',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('created_at', sa.DateTime(), nullable=True),
        sa.Column('updated_at', sa.DateTime(), nullable=True),
        sa.Column('created_by_id', sa.Integer(), nullable=True),
        sa.Column('org_id', sa.Integer(), nullable=True),
        sa.Column('provider_name', sa.String(), nullable=True),
        sa.Column('idp_metadata_url', sa.String(), nullable=True),
        sa.Column('entity_id', sa.String(), nullable=True),
        sa.Column('login_url', sa.String(), nullable=True),
        sa.Column('x509_cert', sa.Text(), nullable=True),
        sa.Column('auto_join_from_domain', sa.String(), nullable=True),
        sa.ForeignKeyConstraint(['created_by_id'], ['users.id'], ondelete='SET NULL'),
        sa.ForeignKeyConstraint(['org_id'], ['organizations.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_organization_sso_config_org_id'), 'organization_sso_config', ['org_id'], unique=True)
    op.create_index(op.f('ix_organization_sso_config_auto_join_from_domain'), 'organization_sso_config', ['auto_join_from_domain'], unique=True)

    op.add_column('users', sa.Column('email_validated', sa.Boolean(), nullable=True))
    op.add_column('users', sa.Column('email_validated_at', sa.DateTime(), nullable=True))

    op.execute("""
        UPDATE users SET email_validated = true WHERE 'google' = ANY(auth_providers) OR 'office365' = ANY(auth_providers) OR 'github' = ANY(auth_providers)
    """)

    op.execute("""
        INSERT INTO organization_sso_config (created_at, created_by_id, org_id, provider_name, auto_join_from_domain)
        SELECT i.created_at, i.created_by_id, i.org_id, 'google', i.account
        FROM integrations i JOIN organizations o ON o.id = i.org_id LEFT JOIN billing_accounts ba ON ba.id = o.billing_account_id
        WHERE i.name = 'gsuite' AND i.authorized AND (ba.plan_status = 'active' OR o.billing_account_id IS NULL)
    """)

    op.execute("""
        DELETE FROM integrations WHERE name='gsuite'
    """)


def downgrade():
    op.drop_table('organization_sso_config')
    op.drop_column('users', 'email_validated')
    op.drop_column('users', 'email_validated_at')
