"""Store only local parts of JIDs

Revision ID: 39ce1636571a
Revises: bdf1c8b85ea3
Create Date: 2026-07-15 21:20:54.149210

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "39ce1636571a"
down_revision: str | None = "bdf1c8b85ea3"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    _update("contact")
    _update("room")


def _update(table: str) -> None:
    with op.batch_alter_table(table, schema=None) as batch_op:
        batch_op.add_column(sa.Column("jid_localpart", sa.String(), nullable=True))
    op.execute(
        sa.text(
            f"UPDATE {table} SET jid_localpart = SUBSTR(jid, 1, INSTR(jid, '@') - 1)"
        )
    )
    with op.batch_alter_table(table, schema=None) as batch_op:
        batch_op.alter_column("jid_localpart", nullable=False)
        batch_op.create_unique_constraint(
            f"uq_{table}_user_account_id_jid_localpart",
            ["user_account_id", "jid_localpart"],
        )
    with op.batch_alter_table(table, schema=None) as batch_op:
        batch_op.drop_constraint(
            batch_op.f(f"uq_{table}_user_account_id_jid"), type_="unique"
        )
        batch_op.drop_column("jid")


def downgrade() -> None:
    raise RuntimeError("Downgrades are not permitted. Clear slidge's home dir.")
