"""Added User Import Source

Peek Plugin Database Migration Script

Revision ID: 43df0e05c728
Revises: b09fe7b3b31b
Create Date: 2022-03-10 12:38:29.301419

"""

# revision identifiers, used by Alembic.
from sqlalchemy.dialects import postgresql

revision = "43df0e05c728"
down_revision = "b09fe7b3b31b"
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa
import geoalchemy2


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    # add user authentication target
    op.add_column(
        "InternalUser",
        sa.Column(
            "authenticationTarget",
            sa.String(),
            nullable=True,
        ),
        schema="core_user",
    )

    # this migration does not work if there're existing users created by LDAP.
    #  Peek Admin needs to delete them before these users log in.
    op.execute(
        """
        UPDATE core_user."InternalUser"
        SET "authenticationTarget" = 'INTERNAL';
        """
    )

    # set `authenticationTarget` not null
    op.alter_column(
        "InternalUser",
        "authenticationTarget",
        nullable=False,
        schema="core_user",
    )

    # add user import source
    op.add_column(
        "InternalUser",
        sa.Column(
            "importSource",
            sa.String(),
            nullable=True,
        ),
        schema="core_user",
    )

    # START of labeling user import sources
    #  enmac-imported users
    op.execute(
        """
        UPDATE core_user."InternalUser"
        SET "importSource" = 'ENMAC'
        WHERE
            "importHash" LIKE 'pof_loader:%';
        """
    )
    # LDAP users
    op.execute(
        """
        UPDATE core_user."InternalUser"
        SET "importSource" = 'LDAP'
        WHERE
            "importHash" LIKE 'peek_core_user.LdapAuth:%';
        """
    )
    #  other users - undetermined
    op.execute(
        """
        UPDATE core_user."InternalUser"
        SET "importSource" = 'UNDETERMINED'
        WHERE
            "importSource" IS NULL;
        """
    )
    # END of labeling user import sources

    # set `importSource` not null
    op.alter_column(
        "InternalUser", "importSource", nullable=False, schema="core_user"
    )

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("InternalUser", "authenticationTarget", "core_user")
    op.drop_column("InternalUser", "importSource", "core_user")
    # ### end Alembic commands ###
