"""Remove bogus unique constraints on room table

Revision ID: 15b0bd83407a
Revises: 45c24cc73c91
Create Date: 2024-08-28 06:57:25.022994

"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

import slidge.db.meta

# revision identifiers, used by Alembic.
revision: str = "15b0bd83407a"
down_revision: Union[str, None] = "45c24cc73c91"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

meta = sa.MetaData()
room_table = sa.Table(
    "room",
    meta,
    sa.Column("id", sa.Integer(), nullable=False),
    sa.Column("user_account_id", sa.Integer(), nullable=False),
    sa.Column("legacy_id", sa.String(), nullable=False),
    sa.Column("jid", slidge.db.meta.JIDType(), nullable=False),
    sa.Column("avatar_id", sa.Integer(), nullable=True),
    sa.Column("name", sa.String(), nullable=True),
    sa.Column("description", sa.String(), nullable=True),
    sa.Column("subject", sa.String(), nullable=True),
    sa.Column("subject_date", sa.DateTime(), nullable=True),
    sa.Column("subject_setter", sa.String(), nullable=True),
    sa.Column("n_participants", sa.Integer(), nullable=True),
    sa.Column(
        "muc_type",
        sa.Enum("GROUP", "CHANNEL", "CHANNEL_NON_ANONYMOUS", name="muctype"),
        nullable=True,
    ),
    sa.Column("user_nick", sa.String(), nullable=True),
    sa.Column("user_resources", sa.String(), nullable=True),
    sa.Column("participants_filled", sa.Boolean(), nullable=False),
    sa.Column("history_filled", sa.Boolean(), nullable=False),
    sa.Column("extra_attributes", slidge.db.meta.JSONEncodedDict(), nullable=True),
    sa.Column("updated", sa.Boolean(), nullable=False),
    sa.Column("avatar_legacy_id", sa.String(), nullable=True),
    sa.ForeignKeyConstraint(
        ["avatar_id"],
        ["avatar.id"],
    ),
    sa.ForeignKeyConstraint(
        ["user_account_id"],
        ["user_account.id"],
    ),
    sa.PrimaryKeyConstraint("id"),
)


def upgrade() -> None:
    if op.get_bind().engine.name == "postgresql":
        return
    with op.batch_alter_table(
        "room",
        schema=None,
        # without copy_from, the newly created table keeps the constraints
        # we actually want to ditch.
        copy_from=room_table,
    ) as batch_op:
        batch_op.create_unique_constraint(
            "uq_room_user_account_id_jid", ["user_account_id", "jid"]
        )
        batch_op.create_unique_constraint(
            "uq_room_user_account_id_legacy_id", ["user_account_id", "legacy_id"]
        )


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("room", schema=None) as batch_op:
        batch_op.drop_constraint("uq_room_user_account_id_legacy_id", type_="unique")
        batch_op.drop_constraint("uq_room_user_account_id_jid", type_="unique")

    # ### end Alembic commands ###
