"""Add unique constraint to agents.openclaw_session_id.

Revision ID: c1d2e3f4a5b6
Revises: b6c7d8e9f0a1
Create Date: 2026-05-20 12:00:00.000000

"""

from __future__ import annotations

from alembic import op

revision = "c1d2e3f4a5b6"
down_revision = "b6c7d8e9f0a1"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Drop the plain index first, then replace with a unique one.
    # NULL values are excluded from unique constraints in PostgreSQL so
    # multiple agents with NULL openclaw_session_id are still allowed.
    op.drop_index("ix_agents_openclaw_session_id", table_name="agents")
    op.create_index(
        "ix_agents_openclaw_session_id",
        "agents",
        ["openclaw_session_id"],
        unique=True,
        postgresql_where="openclaw_session_id IS NOT NULL",
    )


def downgrade() -> None:
    op.drop_index("ix_agents_openclaw_session_id", table_name="agents")
    op.create_index(
        "ix_agents_openclaw_session_id",
        "agents",
        ["openclaw_session_id"],
        unique=False,
    )
