"""Allow duplicated session names across different user

Revision ID: a4289ef5f0cd
Revises: 25ac68cb28ba
Create Date: 2025-12-18 10:45:02.643554

"""

from alembic import op

# revision identifiers, used by Alembic.
revision = "a4289ef5f0cd"
down_revision = "6f8a4c0d2e3g"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # Drop old index if exists (safe for already-migrated databases)
    op.execute(
        """
        DROP INDEX IF EXISTS ix_sessions_unique_name_nonterminal;
        """
    )
    # Create new index if not exists (safe for already-migrated databases)
    op.execute(
        """
        CREATE UNIQUE INDEX IF NOT EXISTS ix_sessions_unique_name_per_user_nonterminal
        ON sessions (name, user_uuid)
        WHERE status NOT IN ('ERROR', 'TERMINATED', 'CANCELLED');
        """
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    # Drop new index if exists (safe for rollback scenarios)
    op.execute(
        """
        DROP INDEX IF EXISTS ix_sessions_unique_name_per_user_nonterminal;
        """
    )
    # Recreate old index if not exists (safe for rollback scenarios)
    op.execute(
        """
        CREATE UNIQUE INDEX IF NOT EXISTS ix_sessions_unique_name_nonterminal
        ON sessions (name)
        WHERE ((status)::text <> ALL ((ARRAY['ERROR'::character varying, 'TERMINATED'::character varying, 'CANCELLED'::character varying])::text[]));
        """
    )
    # ### end Alembic commands ###
