"""add "affiliations", "access_model" and "publish_model" to PubsubNode

Revision ID: 8db042adb973
Revises: 6af2d8f6be76
Create Date: 2025-08-02 12:03:19.726497

"""

from alembic import op
import sqlalchemy as sa
from libervia.backend.memory.sqla_mapping import JID


# revision identifiers, used by Alembic.
revision = "8db042adb973"
down_revision = "6af2d8f6be76"
branch_labels = None
depends_on = None


def upgrade():
    op.create_table(
        "pubsub_affiliations",
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column("node_id", sa.Integer(), nullable=False),
        sa.Column("entity", JID(), nullable=False),
        sa.Column(
            "affiliation",
            sa.Enum(
                "outcast",
                "member",
                "publisher",
                "owner",
                name="affiliation",
                create_constraint=True,
            ),
            nullable=False,
        ),
        sa.ForeignKeyConstraint(
            ["node_id"],
            ["pubsub_nodes.id"],
            name=op.f("fk_pubsub_affiliations_node_id_pubsub_nodes"),
            ondelete="CASCADE",
        ),
        sa.PrimaryKeyConstraint("id", name=op.f("pk_pubsub_affiliations")),
        sa.UniqueConstraint(
            "node_id", "entity", name=op.f("uq_pubsub_affiliations_node_id")
        ),
    )
    with op.batch_alter_table("pubsub_nodes", schema=None) as batch_op:
        batch_op.add_column(
            sa.Column(
                "access_model",
                sa.Enum("open", "whitelist", name="accessmodel", create_constraint=True),
                nullable=True,
            )
        )
        batch_op.add_column(
            sa.Column(
                "publish_model",
                sa.Enum(
                    "publishers",
                    "subscribers",
                    "open",
                    name="publishmodel",
                    create_constraint=True,
                ),
                nullable=True,
            )
        )


def downgrade():
    with op.batch_alter_table("pubsub_nodes", schema=None) as batch_op:
        batch_op.drop_column("publish_model")
        batch_op.drop_column("access_model")

    op.drop_table("pubsub_affiliations")
