"""tenant firm type and engagement review partner

Revision ID: 20260502_tenant_firm_type_review_partner
Revises: 20260501_services_engagement_type
Create Date: 2026-05-02
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "20260502_tenant_firm_type_review_partner"
down_revision: Union[str, None] = "20260501_services_engagement_type"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def _has_column(table_name: str, column_name: str) -> bool:
    bind = op.get_bind()
    insp = sa.inspect(bind)
    return any(c["name"] == column_name for c in insp.get_columns(table_name))


def _has_index(table_name: str, index_name: str) -> bool:
    bind = op.get_bind()
    insp = sa.inspect(bind)
    return any(ix.get("name") == index_name for ix in insp.get_indexes(table_name))


def _create_index_if_missing(table_name: str, index_name: str, columns: list[str]) -> None:
    if not _has_index(table_name, index_name):
        op.create_index(index_name, table_name, columns)


def upgrade() -> None:
    if not _has_column("tenants", "firm_type"):
        op.add_column(
            "tenants",
            sa.Column("firm_type", sa.String(length=30), nullable=False, server_default="proprietorship"),
        )
    _create_index_if_missing("tenants", "ix_tenants_firm_type", ["firm_type"])

    if not _has_column("client_service_subscriptions", "review_partner_user_id"):
        op.add_column(
            "client_service_subscriptions",
            sa.Column("review_partner_user_id", sa.Integer(), nullable=True),
        )
    _create_index_if_missing(
        "client_service_subscriptions",
        "ix_client_service_subscriptions_review_partner_user_id",
        ["review_partner_user_id"],
    )


def downgrade() -> None:
    if _has_index("client_service_subscriptions", "ix_client_service_subscriptions_review_partner_user_id"):
        op.drop_index("ix_client_service_subscriptions_review_partner_user_id", table_name="client_service_subscriptions")
    if _has_column("client_service_subscriptions", "review_partner_user_id"):
        op.drop_column("client_service_subscriptions", "review_partner_user_id")

    if _has_index("tenants", "ix_tenants_firm_type"):
        op.drop_index("ix_tenants_firm_type", table_name="tenants")
    if _has_column("tenants", "firm_type"):
        op.drop_column("tenants", "firm_type")
