"""add sso auto registration and chat source isolation

Revision ID: 0030_sso_chat_source
Revises: 0029_sso_integration
"""

from __future__ import annotations

from alembic import op
import sqlalchemy as sa


revision = "0030_sso_chat_source"
down_revision = "0029_sso_integration"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.add_column(
        "sys_sso_client",
        sa.Column("allow_auto_register", sa.Integer(), nullable=False, server_default="0"),
    )
    op.add_column(
        "sys_sso_client",
        sa.Column("default_entitlement_plan_id", sa.BigInteger(), nullable=True),
    )

    op.add_column(
        "sys_user",
        sa.Column("registration_source", sa.String(length=30), nullable=False, server_default="direct"),
    )
    op.add_column("sys_user", sa.Column("registration_client_id", sa.BigInteger(), nullable=True))
    op.create_index("ix_sys_user_registration_client_id", "sys_user", ["registration_client_id"])

    op.add_column(
        "sys_chat_session",
        sa.Column("source_type", sa.String(length=20), nullable=False, server_default="direct"),
    )
    op.add_column("sys_chat_session", sa.Column("source_client_id", sa.BigInteger(), nullable=True))
    op.create_index(
        "ix_chat_session_user_source_active_updated",
        "sys_chat_session",
        ["user_id", "source_type", "source_client_id", "is_deleted", "updated_at"],
    )


def downgrade() -> None:
    op.drop_index("ix_chat_session_user_source_active_updated", table_name="sys_chat_session")
    op.drop_column("sys_chat_session", "source_client_id")
    op.drop_column("sys_chat_session", "source_type")
    op.drop_index("ix_sys_user_registration_client_id", table_name="sys_user")
    op.drop_column("sys_user", "registration_client_id")
    op.drop_column("sys_user", "registration_source")
    op.drop_column("sys_sso_client", "default_entitlement_plan_id")
    op.drop_column("sys_sso_client", "allow_auto_register")
