"""Phase 1: Add tenant_id and node_id columns (nullable) with composite indexes.

Data isolation spec Section 2.2 Phase 1.

Revision ID: 7a1b2c3d4e5f
Revises: 6b2c3d4e5f6g
Create Date: 2026-03-13 10:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID

# revision identifiers, used by Alembic.
revision: str = "7a1b2c3d4e5f"
down_revision: Union[str, None] = "6b2c3d4e5f6g"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # --- documents ---
    op.add_column("documents", sa.Column("tenant_id", UUID(as_uuid=True), nullable=True))
    op.add_column("documents", sa.Column("node_id", UUID(as_uuid=True), nullable=True))
    op.create_index("idx_documents_tenant_node", "documents", ["tenant_id", "node_id"])

    # --- extracted_records ---
    op.add_column("extracted_records", sa.Column("tenant_id", UUID(as_uuid=True), nullable=True))
    op.add_column("extracted_records", sa.Column("node_id", UUID(as_uuid=True), nullable=True))
    op.create_index(
        "idx_extracted_records_tenant_node", "extracted_records", ["tenant_id", "node_id"]
    )

    # --- domain_term_dictionary ---
    op.add_column("domain_term_dictionary", sa.Column("tenant_id", UUID(as_uuid=True), nullable=True))
    op.add_column("domain_term_dictionary", sa.Column("node_id", UUID(as_uuid=True), nullable=True))
    op.create_index(
        "idx_domain_terms_tenant_node", "domain_term_dictionary", ["tenant_id", "node_id"]
    )

    # --- symbol_dictionaries ---
    op.add_column("symbol_dictionaries", sa.Column("tenant_id", UUID(as_uuid=True), nullable=True))
    op.add_column("symbol_dictionaries", sa.Column("node_id", UUID(as_uuid=True), nullable=True))
    op.create_index(
        "idx_symbol_dict_tenant_node", "symbol_dictionaries", ["tenant_id", "node_id"]
    )


def downgrade() -> None:
    for table, idx_name in [
        ("symbol_dictionaries", "idx_symbol_dict_tenant_node"),
        ("domain_term_dictionary", "idx_domain_terms_tenant_node"),
        ("extracted_records", "idx_extracted_records_tenant_node"),
        ("documents", "idx_documents_tenant_node"),
    ]:
        op.drop_index(idx_name, table_name=table)
        op.drop_column(table, "node_id")
        op.drop_column(table, "tenant_id")
