"""add "presence" access model to PubsubNode + cleanup

Revision ID: 3ddac15a0a39
Revises: 007439b3b0ce
Create Date: 2026-04-15 08:55:32.891237

"""

from alembic import op
from sqlalchemy import inspect
from sqlalchemy.schema import conv

# revision identifiers, used by Alembic.
revision = "3ddac15a0a39"
down_revision = "007439b3b0ce"
branch_labels = None
depends_on = None


def _existing_check_constraints(table_name: str) -> set[str | None]:
    insp = inspect(op.get_bind())
    return {c["name"] for c in insp.get_check_constraints(table_name) if c.get("name")}


def upgrade():
    existing = _existing_check_constraints("pubsub_nodes")

    with op.batch_alter_table("pubsub_nodes") as batch_op:
        # remove legacy duplicate constraints if present
        if "accessmodel" in existing:
            batch_op.drop_constraint(conv("accessmodel"), type_="check")
        if "publishmodel" in existing:
            batch_op.drop_constraint(conv("publishmodel"), type_="check")

        if "ck_pubsub_nodes_accessmodel" in existing:
            batch_op.drop_constraint(conv("ck_pubsub_nodes_accessmodel"), type_="check")

        batch_op.create_check_constraint(
            "accessmodel",
            "access_model IN ('open', 'presence', 'whitelist')",
        )


def downgrade():
    with op.batch_alter_table("pubsub_nodes") as batch_op:
        batch_op.drop_constraint("accessmodel", type_="check")

        batch_op.create_check_constraint(
            "accessmodel",
            "access_model IN ('open', 'whitelist')",
        )
