
"""reconcile common tables and clients safely

Revision ID: 7f1c9b2d4a10
Revises: 3d5ce4b11767
Create Date: 2026-04-05 14:30:00.000000

NOTE:
- This is a manual repair/reconciliation migration.
- It is intentionally written to CREATE missing tables/indexes only.
- It does NOT drop existing tables.
- It is safe for the current state where revision 3d5ce4b11767 has already been applied.
"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "7f1c9b2d4a10"
down_revision: Union[str, None] = "940fb75ddce6"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


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


def _has_table(table_name: str) -> bool:
    return table_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: list[str], unique: bool = False) -> None:
    if not _has_index(table_name, index_name):
        op.create_index(index_name, table_name, columns, unique=unique)


def upgrade() -> None:
    if not _has_table("audit_logs"):
        op.create_table(
            "audit_logs",
            sa.Column("id", sa.Integer(), primary_key=True, nullable=False),
            sa.Column("created_at_utc", sa.DateTime(), nullable=False),
            sa.Column("actor_user_id", sa.Integer(), nullable=True),
            sa.Column("actor_email", sa.String(length=255), nullable=True),
            sa.Column("actor_tenant_id", sa.Integer(), nullable=True),
            sa.Column("actor_branch_id", sa.Integer(), nullable=True),
            sa.Column("action", sa.String(length=120), nullable=False),
            sa.Column("entity_type", sa.String(length=120), nullable=False),
            sa.Column("entity_id", sa.String(length=120), nullable=True),
            sa.Column("entity_name", sa.String(length=255), nullable=True),
            sa.Column("status", sa.String(length=30), nullable=False),
            sa.Column("target_tenant_id", sa.Integer(), nullable=True),
            sa.Column("target_branch_id", sa.Integer(), nullable=True),
            sa.Column("ip_address", sa.String(length=100), nullable=True),
            sa.Column("user_agent", sa.String(length=500), nullable=True),
            sa.Column("details_json", sa.Text(), nullable=False),
            sa.ForeignKeyConstraint(["actor_user_id"], ["users.id"], ondelete="SET NULL"),
        )

    _create_index_if_missing("audit_logs", "ix_audit_logs_action", ["action"])
    _create_index_if_missing("audit_logs", "ix_audit_logs_actor_branch_id", ["actor_branch_id"])
    _create_index_if_missing("audit_logs", "ix_audit_logs_actor_tenant_id", ["actor_tenant_id"])
    _create_index_if_missing("audit_logs", "ix_audit_logs_actor_user_id", ["actor_user_id"])
    _create_index_if_missing("audit_logs", "ix_audit_logs_created_at_utc", ["created_at_utc"])
    _create_index_if_missing("audit_logs", "ix_audit_logs_entity_type", ["entity_type"])
    _create_index_if_missing("audit_logs", "ix_audit_logs_status", ["status"])
    _create_index_if_missing("audit_logs", "ix_audit_logs_target_branch_id", ["target_branch_id"])
    _create_index_if_missing("audit_logs", "ix_audit_logs_target_tenant_id", ["target_tenant_id"])

    if not _has_table("services"):
        op.create_table(
            "services",
            sa.Column("id", sa.Integer(), primary_key=True, nullable=False),
            sa.Column("tenant_id", sa.Integer(), nullable=False),
            sa.Column("branch_id", sa.Integer(), nullable=False),
            sa.Column("service_code", sa.String(length=50), nullable=False),
            sa.Column("service_name", sa.String(length=200), nullable=False),
            sa.Column("category", sa.String(length=100), nullable=True),
            sa.Column("description", sa.Text(), nullable=True),
            sa.Column("is_active", sa.Boolean(), nullable=False),
            sa.Column("is_client_requestable", sa.Boolean(), nullable=False),
            sa.Column("is_consultant_requestable", sa.Boolean(), nullable=False),
            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),
            sa.Column("updated_at_utc", sa.DateTime(), nullable=False),
            sa.ForeignKeyConstraint(["tenant_id"], ["tenants.id"]),
            sa.ForeignKeyConstraint(["branch_id"], ["branches.id"]),
            sa.ForeignKeyConstraint(["created_by_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["updated_by_user_id"], ["users.id"]),
            sa.UniqueConstraint("tenant_id", "branch_id", "service_code", name="uq_services_tenant_branch_code"),
        )

    _create_index_if_missing("services", "ix_services_tenant_id", ["tenant_id"])
    _create_index_if_missing("services", "ix_services_branch_id", ["branch_id"])
    _create_index_if_missing("services", "ix_services_service_code", ["service_code"])
    _create_index_if_missing("services", "ix_services_service_name", ["service_name"])

    if not _has_table("service_task_templates"):
        op.create_table(
            "service_task_templates",
            sa.Column("id", sa.Integer(), primary_key=True, nullable=False),
            sa.Column("service_id", sa.Integer(), nullable=False),
            sa.Column("task_name", sa.String(length=200), nullable=False),
            sa.Column("description", sa.Text(), nullable=True),
            sa.Column("sequence_no", sa.Integer(), nullable=False),
            sa.Column("default_role_name", sa.String(length=100), nullable=True),
            sa.Column("is_mandatory", sa.Boolean(), nullable=False),
            sa.Column("requires_review", sa.Boolean(), nullable=False),
            sa.Column("is_active", sa.Boolean(), nullable=False),
            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),
            sa.Column("updated_at_utc", sa.DateTime(), nullable=False),
            sa.ForeignKeyConstraint(["service_id"], ["services.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["created_by_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["updated_by_user_id"], ["users.id"]),
            sa.UniqueConstraint("service_id", "sequence_no", name="uq_service_task_templates_sequence"),
        )

    _create_index_if_missing("service_task_templates", "ix_service_task_templates_service_id", ["service_id"])

    if not _has_table("invite_tokens"):
        op.create_table(
            "invite_tokens",
            sa.Column("id", sa.Integer(), primary_key=True, nullable=False),
            sa.Column("user_id", sa.Integer(), nullable=False),
            sa.Column("token_hash", sa.String(length=64), nullable=False),
            sa.Column("created_at_utc", sa.DateTime(), nullable=False),
            sa.Column("expires_at_utc", sa.DateTime(), nullable=False),
            sa.Column("used_at_utc", sa.DateTime(), nullable=True),
            sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
            sa.UniqueConstraint("token_hash", name="uq_invite_token_hash"),
        )

    _create_index_if_missing("invite_tokens", "ix_invite_tokens_user_id", ["user_id"])
    _create_index_if_missing("invite_tokens", "ix_invite_tokens_token_hash", ["token_hash"])

    if not _has_table("password_reset_tokens"):
        op.create_table(
            "password_reset_tokens",
            sa.Column("id", sa.Integer(), primary_key=True, nullable=False),
            sa.Column("user_id", sa.Integer(), nullable=False),
            sa.Column("token_hash", sa.String(length=64), nullable=False),
            sa.Column("created_at_utc", sa.DateTime(), nullable=False),
            sa.Column("expires_at_utc", sa.DateTime(), nullable=False),
            sa.Column("used_at_utc", sa.DateTime(), nullable=True),
            sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
            sa.UniqueConstraint("token_hash", name="uq_password_reset_token_hash"),
        )

    _create_index_if_missing("password_reset_tokens", "ix_password_reset_tokens_user_id", ["user_id"])
    _create_index_if_missing("password_reset_tokens", "ix_password_reset_tokens_token_hash", ["token_hash"])

    if not _has_table("clients"):
        op.create_table(
            "clients",
            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=False),
            sa.Column("partner_id", sa.Integer(), nullable=False),
            sa.Column("client_code", sa.String(length=50), nullable=False),
            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("cin_llpin", sa.String(length=30), nullable=True),
            sa.Column("msme_no", sa.String(length=50), nullable=True),
            sa.Column("iec_code", sa.String(length=30), nullable=True),
            sa.Column("contact_person_name", sa.String(length=200), nullable=True),
            sa.Column("contact_person_designation", sa.String(length=200), nullable=True),
            sa.Column("mobile", sa.String(length=20), nullable=True),
            sa.Column("alternate_mobile", sa.String(length=20), nullable=True),
            sa.Column("email", sa.String(length=255), nullable=True),
            sa.Column("alternate_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("status", sa.String(length=20), nullable=False, server_default="active"),
            sa.Column("client_category", sa.String(length=100), nullable=True),
            sa.Column("risk_category", sa.String(length=50), nullable=True),
            sa.Column("onboarding_date", sa.Date(), nullable=True),
            sa.Column("closing_date", sa.Date(), nullable=True),
            sa.Column("notes", sa.Text(), nullable=True),
            sa.Column("gst_applicable", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("income_tax_applicable", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("tds_applicable", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("roc_applicable", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("audit_applicable", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("pf_applicable", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("esi_applicable", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("professional_tax_applicable", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("payroll_applicable", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("msme_applicable", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("import_export_applicable", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.text("true")),
            sa.Column("is_archived", sa.Boolean(), nullable=False, server_default=sa.text("false")),
            sa.Column("archived_at_utc", sa.DateTime(timezone=True), nullable=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(timezone=True), nullable=False),
            sa.Column("updated_at_utc", sa.DateTime(timezone=True), nullable=False),
            sa.ForeignKeyConstraint(["tenant_id"], ["tenants.id"]),
            sa.ForeignKeyConstraint(["branch_id"], ["branches.id"]),
            sa.ForeignKeyConstraint(["partner_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["created_by_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["updated_by_user_id"], ["users.id"]),
            sa.UniqueConstraint("tenant_id", "client_code", name="uq_clients_tenant_code"),
            sa.UniqueConstraint("tenant_id", "pan", name="uq_clients_tenant_pan"),
            sa.UniqueConstraint("tenant_id", "gstin", name="uq_clients_tenant_gstin"),
        )

    _create_index_if_missing("clients", "ix_clients_tenant_id", ["tenant_id"])
    _create_index_if_missing("clients", "ix_clients_branch_id", ["branch_id"])
    _create_index_if_missing("clients", "ix_clients_partner_id", ["partner_id"])
    _create_index_if_missing("clients", "ix_clients_client_code", ["client_code"])
    _create_index_if_missing("clients", "ix_clients_client_name", ["client_name"])
    _create_index_if_missing("clients", "ix_clients_pan", ["pan"])
    _create_index_if_missing("clients", "ix_clients_gstin", ["gstin"])
    _create_index_if_missing("clients", "ix_clients_status", ["status"])

    if not _has_table("client_audit_logs"):
        op.create_table(
            "client_audit_logs",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True, nullable=False),
            sa.Column("client_id", sa.Integer(), nullable=False),
            sa.Column("tenant_id", sa.Integer(), nullable=False),
            sa.Column("branch_id", sa.Integer(), nullable=False),
            sa.Column("actor_user_id", sa.Integer(), nullable=True),
            sa.Column("action", sa.String(length=50), nullable=False),
            sa.Column("summary", sa.String(length=255), nullable=False),
            sa.Column("payload_json", sa.JSON(), nullable=True),
            sa.Column("created_at_utc", sa.DateTime(timezone=True), nullable=False),
            sa.ForeignKeyConstraint(["client_id"], ["clients.id"]),
            sa.ForeignKeyConstraint(["tenant_id"], ["tenants.id"]),
            sa.ForeignKeyConstraint(["branch_id"], ["branches.id"]),
            sa.ForeignKeyConstraint(["actor_user_id"], ["users.id"]),
        )

    _create_index_if_missing("client_audit_logs", "ix_client_audit_logs_client_id", ["client_id"])
    _create_index_if_missing("client_audit_logs", "ix_client_audit_logs_tenant_id", ["tenant_id"])
    _create_index_if_missing("client_audit_logs", "ix_client_audit_logs_branch_id", ["branch_id"])
    _create_index_if_missing("client_audit_logs", "ix_client_audit_logs_action", ["action"])


def downgrade() -> None:
    # Intentionally conservative:
    # only remove tables introduced by this repair migration that are not baseline-owned.
    # We do NOT drop services/auth-flow/audit tables here to avoid accidental data loss.
    if _has_table("client_audit_logs"):
        op.drop_table("client_audit_logs")
    if _has_table("clients"):
        op.drop_table("clients")
