"""Add User identity verification fields

Revision ID: fe68dfd0eac2
Revises: 294d746cd4a8
Create Date: 2025-05-06 12:57:23.940807

"""

import sqlalchemy as sa
from alembic import op

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "fe68dfd0eac2"
down_revision = "294d746cd4a8"
branch_labels: tuple[str] | None = None
depends_on: tuple[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "users", sa.Column("identity_verification_status", sa.String(), nullable=True)
    )
    op.execute("UPDATE users SET identity_verification_status = 'unverified'")
    op.execute(
        """
        UPDATE users
        SET identity_verification_status = 'verified'
        WHERE meta->>'identity' IS NOT NULL
        """
    )
    op.alter_column("users", "identity_verification_status", nullable=False)

    op.add_column(
        "users", sa.Column("identity_verification_id", sa.String(), nullable=True)
    )
    op.create_unique_constraint(
        op.f("users_identity_verification_id_key"),
        "users",
        ["identity_verification_id"],
    )
    op.execute(
        """
        UPDATE users
        SET identity_verification_id = meta->>'identity'
        WHERE meta->>'identity' IS NOT NULL
        """
    )
    op.execute(
        """
        UPDATE users
        SET meta = meta - 'identity'
        WHERE meta->>'identity' IS NOT NULL
        """
    )

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        op.f("users_identity_verification_id_key"), "users", type_="unique"
    )
    op.drop_column("users", "identity_verification_id")
    op.drop_column("users", "identity_verified")
    # ### end Alembic commands ###
