"""identity properties jsonb to json

Revision ID: fdcdafdb11cf
Revises: 549eff097c71
Create Date: 2025-02-21 10:30:49.937854

"""

from typing import Sequence, Union

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op
from letta.settings import settings

# revision identifiers, used by Alembic.
revision: str = "fdcdafdb11cf"
down_revision: Union[str, None] = "549eff097c71"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Skip this migration for SQLite
    if not settings.letta_pg_uri_no_default:
        return

    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column(
        "identities",
        "properties",
        existing_type=postgresql.JSONB(astext_type=sa.Text()),
        type_=postgresql.JSON(astext_type=sa.Text()),
        existing_nullable=False,
        existing_server_default=sa.text("'[]'::jsonb"),
    )
    op.drop_constraint("unique_identifier_without_project", "identities", type_="unique")
    op.create_unique_constraint(
        "unique_identifier_key_project_id_organization_id",
        "identities",
        ["identifier_key", "project_id", "organization_id"],
        postgresql_nulls_not_distinct=True,
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # Skip this migration for SQLite
    if not settings.letta_pg_uri_no_default:
        return

    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint("unique_identifier_key_project_id_organization_id", "identities", type_="unique")
    op.create_unique_constraint(
        "unique_identifier_without_project",
        "identities",
        ["identifier_key", "project_id", "organization_id"],
        postgresql_nulls_not_distinct=True,
    )
    op.alter_column(
        "identities",
        "properties",
        existing_type=postgresql.JSON(astext_type=sa.Text()),
        type_=postgresql.JSONB(astext_type=sa.Text()),
        existing_nullable=False,
        existing_server_default=sa.text("'[]'::jsonb"),
    )
    # ### end Alembic commands ###
