"""Move sources to orm

Revision ID: cda66b6cb0d6
Revises: b6d7ca024aa9
Create Date: 2024-11-07 13:29:57.186107

"""

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 = "cda66b6cb0d6"
down_revision: Union[str, None] = "b6d7ca024aa9"
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.add_column("sources", sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True))
    op.add_column("sources", sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False))
    op.add_column("sources", sa.Column("_created_by_id", sa.String(), nullable=True))
    op.add_column("sources", sa.Column("_last_updated_by_id", sa.String(), nullable=True))

    # Data migration step:
    op.add_column("sources", sa.Column("organization_id", sa.String(), nullable=True))
    # Populate `organization_id` based on `user_id`
    # Use a raw SQL query to update the organization_id
    op.execute(
        """
        UPDATE sources
        SET organization_id = users.organization_id
        FROM users
        WHERE sources.user_id = users.id
    """
    )

    # Set `organization_id` as non-nullable after population
    op.alter_column("sources", "organization_id", nullable=False)

    op.alter_column("sources", "embedding_config", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=False)
    op.drop_index("sources_idx_user", table_name="sources")
    op.create_foreign_key(None, "sources", "organizations", ["organization_id"], ["id"])
    op.drop_column("sources", "user_id")
    # ### 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.add_column("sources", sa.Column("user_id", sa.VARCHAR(), autoincrement=False, nullable=False))
    op.drop_constraint(None, "sources", type_="foreignkey")
    op.create_index("sources_idx_user", "sources", ["user_id"], unique=False)
    op.alter_column("sources", "embedding_config", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=True)
    op.drop_column("sources", "organization_id")
    op.drop_column("sources", "_last_updated_by_id")
    op.drop_column("sources", "_created_by_id")
    op.drop_column("sources", "is_deleted")
    op.drop_column("sources", "updated_at")
    # ### end Alembic commands ###
