"""Add version table

Revision ID: 76dfdbe90d2b
Revises: 11b2402d4be1
Create Date: 2025-09-13 19:38:17.246644

"""

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

# revision identifiers, used by Alembic.
revision = "76dfdbe90d2b"
down_revision = "11b2402d4be1"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "assistant_versions",
        sa.Column("assistant_id", sa.Text(), nullable=False),
        sa.Column("version", sa.Integer(), nullable=False),
        sa.Column("graph_id", sa.Text(), nullable=False),
        sa.Column("config", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column("context", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column(
            "created_at",
            sa.TIMESTAMP(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.Column(
            "metadata",
            postgresql.JSONB(astext_type=sa.Text()),
            server_default=sa.text("'{}'::jsonb"),
            nullable=False,
        ),
        sa.Column("name", sa.Text(), nullable=True),
        sa.Column("description", sa.Text(), nullable=True),
        sa.ForeignKeyConstraint(
            ["assistant_id"],
            ["assistant.assistant_id"],
        ),
        sa.PrimaryKeyConstraint("assistant_id", "version"),
    )
    op.add_column(
        "assistant",
        sa.Column("version", sa.Integer(), server_default=sa.text("1"), nullable=False),
    )
    op.drop_index(op.f("idx_assistant_user_graph"), table_name="assistant")
    op.create_index(
        "idx_assistant_user_assistant",
        "assistant",
        ["user_id", "assistant_id"],
        unique=True,
    )
    op.create_index(
        "idx_assistant_user_graph_config",
        "assistant",
        ["user_id", "graph_id", "config"],
        unique=True,
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index("idx_assistant_user_graph_config", table_name="assistant")
    op.drop_index("idx_assistant_user_assistant", table_name="assistant")
    op.create_index(
        op.f("idx_assistant_user_graph"),
        "assistant",
        ["user_id", "graph_id"],
        unique=True,
    )
    op.drop_column("assistant", "version")
    op.drop_table("assistant_versions")
    # ### end Alembic commands ###
