"""Migrate blocks to orm model

Revision ID: f7507eab4bb9
Revises: c85a3d07c028
Create Date: 2024-11-18 15:40:13.149438

"""

from typing import Sequence, Union

import sqlalchemy as sa

from alembic import op
from letta.settings import settings

# revision identifiers, used by Alembic.
revision: str = "f7507eab4bb9"
down_revision: Union[str, None] = "c85a3d07c028"
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("block", sa.Column("is_template", sa.Boolean(), nullable=True))
    # Populate `is_template` column
    op.execute(
        """
        UPDATE block
        SET is_template = COALESCE(template, FALSE)
        """
    )

    # Step 2: Make `is_template` non-nullable
    op.alter_column("block", "is_template", nullable=False)
    op.add_column("block", 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 block
        SET organization_id = users.organization_id
        FROM users
        WHERE block.user_id = users.id
    """
    )
    op.alter_column("block", "organization_id", nullable=False)
    op.add_column("block", sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True))
    op.add_column("block", sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True))
    op.add_column("block", sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False))
    op.add_column("block", sa.Column("_created_by_id", sa.String(), nullable=True))
    op.add_column("block", sa.Column("_last_updated_by_id", sa.String(), nullable=True))
    op.alter_column("block", "limit", existing_type=sa.BIGINT(), type_=sa.Integer(), nullable=False)
    op.drop_index("block_idx_user", table_name="block")
    op.create_foreign_key(None, "block", "organizations", ["organization_id"], ["id"])
    op.drop_column("block", "template")
    op.drop_column("block", "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("block", sa.Column("user_id", sa.VARCHAR(), autoincrement=False, nullable=True))
    op.add_column("block", sa.Column("template", sa.BOOLEAN(), autoincrement=False, nullable=True))
    op.drop_constraint(None, "block", type_="foreignkey")
    op.create_index("block_idx_user", "block", ["user_id"], unique=False)
    op.alter_column("block", "limit", existing_type=sa.Integer(), type_=sa.BIGINT(), nullable=True)
    op.drop_column("block", "_last_updated_by_id")
    op.drop_column("block", "_created_by_id")
    op.drop_column("block", "is_deleted")
    op.drop_column("block", "updated_at")
    op.drop_column("block", "created_at")
    op.drop_column("block", "organization_id")
    op.drop_column("block", "is_template")
    # ### end Alembic commands ###
