"""Phase 5A.2 consultant-managed clients

Revision ID: 20260509_consultant_managed_clients_phase_5a2
Revises: 20260508_consultant_portal_phase_5a1
Create Date: 2026-05-09
"""

from __future__ import annotations

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "20260509_consultant_managed_clients_phase_5a2"
down_revision: Union[str, None] = "20260508_consultant_portal_phase_5a1"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def _has_table(table_name: str) -> bool:
    bind = op.get_bind()
    inspector = sa.inspect(bind)
    return table_name in inspector.get_table_names()


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


def upgrade() -> None:
    if not _has_table("consultant_managed_clients"):
        op.create_table(
            "consultant_managed_clients",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
            sa.Column("tenant_id", sa.Integer(), sa.ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False),
            sa.Column("branch_id", sa.Integer(), sa.ForeignKey("branches.id"), nullable=True),
            sa.Column("consultant_id", sa.Integer(), sa.ForeignKey("consultant_profiles.id", ondelete="CASCADE"), nullable=False),
            sa.Column("linked_firm_client_id", sa.Integer(), sa.ForeignKey("clients.id", ondelete="SET NULL"), nullable=True),
            sa.Column("client_code", sa.String(length=50), nullable=True),
            sa.Column("client_name", sa.String(length=200), nullable=False),
            sa.Column("trade_name", sa.String(length=200), nullable=True),
            sa.Column("client_type", sa.String(length=100), nullable=False, server_default="Other"),
            sa.Column("pan", sa.String(length=20), nullable=True),
            sa.Column("gstin", sa.String(length=20), nullable=True),
            sa.Column("tan", sa.String(length=20), nullable=True),
            sa.Column("contact_person_name", sa.String(length=200), nullable=True),
            sa.Column("mobile", sa.String(length=20), nullable=True),
            sa.Column("email", sa.String(length=255), nullable=True),
            sa.Column("address_line_1", sa.String(length=255), nullable=True),
            sa.Column("address_line_2", sa.String(length=255), nullable=True),
            sa.Column("city", sa.String(length=100), nullable=True),
            sa.Column("state", sa.String(length=100), nullable=True),
            sa.Column("pincode", sa.String(length=20), nullable=True),
            sa.Column("country", sa.String(length=100), nullable=True, server_default="India"),
            sa.Column("service_interest", sa.Text(), nullable=True),
            sa.Column("relationship_stage", sa.String(length=30), nullable=False, server_default="managed"),
            sa.Column("status", sa.String(length=30), nullable=False, server_default="active"),
            sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()),
            sa.Column("notes", sa.Text(), nullable=True),
            sa.Column("created_by_user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True),
            sa.Column("updated_by_user_id", sa.Integer(), sa.ForeignKey("users.id"), nullable=True),
            sa.Column("created_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
            sa.Column("updated_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
            sa.UniqueConstraint("tenant_id", "consultant_id", "client_code", name="uq_consultant_managed_clients_code"),
        )
        op.create_index("ix_consultant_managed_clients_tenant_id", "consultant_managed_clients", ["tenant_id"])
        op.create_index("ix_consultant_managed_clients_branch_id", "consultant_managed_clients", ["branch_id"])
        op.create_index("ix_consultant_managed_clients_consultant_id", "consultant_managed_clients", ["consultant_id"])
        op.create_index("ix_consultant_managed_clients_linked_firm_client_id", "consultant_managed_clients", ["linked_firm_client_id"])
        op.create_index("ix_consultant_managed_clients_client_code", "consultant_managed_clients", ["client_code"])
        op.create_index("ix_consultant_managed_clients_client_name", "consultant_managed_clients", ["client_name"])
        op.create_index("ix_consultant_managed_clients_pan", "consultant_managed_clients", ["pan"])
        op.create_index("ix_consultant_managed_clients_gstin", "consultant_managed_clients", ["gstin"])
        op.create_index("ix_consultant_managed_clients_email", "consultant_managed_clients", ["email"])
        op.create_index("ix_consultant_managed_clients_relationship_stage", "consultant_managed_clients", ["relationship_stage"])
        op.create_index("ix_consultant_managed_clients_status", "consultant_managed_clients", ["status"])
        op.create_index("ix_consultant_managed_clients_is_active", "consultant_managed_clients", ["is_active"])


def downgrade() -> None:
    if _has_table("consultant_managed_clients"):
        for index_name in [
            "ix_consultant_managed_clients_is_active",
            "ix_consultant_managed_clients_status",
            "ix_consultant_managed_clients_relationship_stage",
            "ix_consultant_managed_clients_email",
            "ix_consultant_managed_clients_gstin",
            "ix_consultant_managed_clients_pan",
            "ix_consultant_managed_clients_client_name",
            "ix_consultant_managed_clients_client_code",
            "ix_consultant_managed_clients_linked_firm_client_id",
            "ix_consultant_managed_clients_consultant_id",
            "ix_consultant_managed_clients_branch_id",
            "ix_consultant_managed_clients_tenant_id",
        ]:
            if _has_index("consultant_managed_clients", index_name):
                op.drop_index(index_name, table_name="consultant_managed_clients")
        op.drop_table("consultant_managed_clients")
