"""add root_id and event_closure table

Revision ID: 01ba80f80708
Revises: f2e20ffcad2d
Create Date: 2025-11-06 14:25:09.042087

"""

import sqlalchemy as sa
from alembic import op

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "01ba80f80708"
down_revision = "f2e20ffcad2d"
branch_labels: tuple[str] | None = None
depends_on: tuple[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "events_closure",
        sa.Column("ancestor_id", sa.Uuid(), nullable=False),
        sa.Column("descendant_id", sa.Uuid(), nullable=False),
        sa.Column("depth", sa.BigInteger(), nullable=False),
        sa.ForeignKeyConstraint(
            ["ancestor_id"],
            ["events.id"],
            name=op.f("events_closure_ancestor_id_fkey"),
            ondelete="cascade",
        ),
        sa.ForeignKeyConstraint(
            ["descendant_id"],
            ["events.id"],
            name=op.f("events_closure_descendant_id_fkey"),
            ondelete="cascade",
        ),
        sa.PrimaryKeyConstraint(
            "ancestor_id", "descendant_id", name=op.f("events_closure_pkey")
        ),
    )
    op.create_index(
        op.f("ix_events_closure_depth"), "events_closure", ["depth"], unique=False
    )
    op.create_index(
        "ix_events_closure_ancestor_descendant",
        "events_closure",
        ["ancestor_id", "descendant_id"],
        unique=False,
    )
    op.create_index(
        "ix_events_closure_descendant_ancestor",
        "events_closure",
        ["descendant_id", "ancestor_id"],
        unique=False,
    )
    op.add_column("events", sa.Column("root_id", sa.Uuid(), nullable=True))
    op.create_index(op.f("ix_events_root_id"), "events", ["root_id"], unique=False)
    op.create_index(
        "ix_events_org_timestamp_id",
        "events",
        ["organization_id", sa.text("timestamp DESC"), "id"],
        unique=False,
    )
    op.create_foreign_key(
        op.f("events_root_id_fkey"), "events", "events", ["root_id"], ["id"]
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(op.f("events_root_id_fkey"), "events", type_="foreignkey")
    op.drop_index("ix_events_org_timestamp_id", table_name="events")
    op.drop_index(op.f("ix_events_root_id"), table_name="events")
    op.drop_column("events", "root_id")
    op.drop_index("ix_events_closure_descendant_ancestor", table_name="events_closure")
    op.drop_index("ix_events_closure_ancestor_descendant", table_name="events_closure")
    op.drop_index(op.f("ix_events_closure_depth"), table_name="events_closure")
    op.drop_table("events_closure")
    # ### end Alembic commands ###
