"""client service subscriptions and lightweight assignment

Revision ID: 20260425_client_service_subscriptions
Revises: 20260424_partner_service_restrictions
Create Date: 2026-04-25 20:00:00.000000
"""

from alembic import op
import sqlalchemy as sa

revision = "20260425_client_service_subscriptions"
down_revision = "20260424_partner_service_restrictions"
branch_labels = None
depends_on = None


def _inspector():
    return sa.inspect(op.get_bind())


def _has_table(name: str) -> bool:
    return name in _inspector().get_table_names()


def _has_index(table_name: str, index_name: str) -> bool:
    try:
        indexes = _inspector().get_indexes(table_name)
    except Exception:
        return False
    return any(ix.get("name") == index_name for ix in indexes)


def _create_index_if_missing(table_name: str, index_name: str, columns, unique: bool = False) -> None:
    if not _has_index(table_name, index_name):
        op.create_index(index_name, table_name, columns, unique=unique)


def upgrade():
    if not _has_table("client_service_subscriptions"):
        op.create_table(
            "client_service_subscriptions",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True, nullable=False),
            sa.Column("tenant_id", sa.Integer(), nullable=False),
            sa.Column("branch_id", sa.Integer(), nullable=True),
            sa.Column("client_id", sa.Integer(), nullable=False),
            sa.Column("service_catalogue_id", sa.Integer(), nullable=False),
            sa.Column("firm_service_selection_id", sa.Integer(), nullable=True),
            sa.Column("assigned_partner_user_id", sa.Integer(), nullable=True),
            sa.Column("assigned_manager_user_id", sa.Integer(), nullable=True),
            sa.Column("assigned_staff_user_id", sa.Integer(), nullable=True),
            sa.Column("start_date", sa.Date(), nullable=True),
            sa.Column("end_date", sa.Date(), nullable=True),
            sa.Column("status", sa.String(length=30), nullable=False, server_default="active"),
            sa.Column("remarks", sa.Text(), nullable=True),
            sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()),
            sa.Column("created_by_user_id", sa.Integer(), nullable=True),
            sa.Column("updated_by_user_id", sa.Integer(), nullable=True),
            sa.Column("created_at_utc", sa.DateTime(), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
            sa.Column("updated_at_utc", sa.DateTime(), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
            sa.ForeignKeyConstraint(["tenant_id"], ["tenants.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["branch_id"], ["branches.id"]),
            sa.ForeignKeyConstraint(["client_id"], ["clients.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["service_catalogue_id"], ["service_catalogues.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["firm_service_selection_id"], ["firm_service_selections.id"], ondelete="SET NULL"),
            sa.ForeignKeyConstraint(["assigned_partner_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["assigned_manager_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["assigned_staff_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["created_by_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["updated_by_user_id"], ["users.id"]),
            sa.UniqueConstraint("tenant_id", "client_id", "service_catalogue_id", name="uq_client_service_subscription_tenant_client_service"),
        )

    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_tenant_id", ["tenant_id"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_branch_id", ["branch_id"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_client_id", ["client_id"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_service_catalogue_id", ["service_catalogue_id"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_firm_service_selection_id", ["firm_service_selection_id"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_assigned_partner_user_id", ["assigned_partner_user_id"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_assigned_manager_user_id", ["assigned_manager_user_id"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_assigned_staff_user_id", ["assigned_staff_user_id"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_status", ["status"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_is_active", ["is_active"])


def downgrade():
    if _has_table("client_service_subscriptions"):
        op.drop_table("client_service_subscriptions")
