"""Phase 1 - UDIN on final documents

Revision ID: 20260621_phase_1_udin_final_documents
Revises: 20260620_phase_204f_platform_smtp
Create Date: 2026-07-06
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect

revision = "20260621_phase_1_udin_final_documents"
down_revision = "20260620_phase_204f_platform_smtp"
branch_labels = None
depends_on = None


def _has_column(bind, table_name: str, column_name: str) -> bool:
    try:
        return column_name in {col["name"] for col in inspect(bind).get_columns(table_name)}
    except Exception:
        return False


def _has_index(bind, table_name: str, index_name: str) -> bool:
    try:
        return index_name in {idx["name"] for idx in inspect(bind).get_indexes(table_name)}
    except Exception:
        return False


def _add_column_if_missing(bind, table_name: str, column: sa.Column) -> None:
    if not _has_column(bind, table_name, column.name):
        with op.batch_alter_table(table_name) as batch:
            batch.add_column(column)


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


def upgrade() -> None:
    bind = op.get_bind()
    if "engagement_documents" not in inspect(bind).get_table_names():
        return

    _add_column_if_missing(bind, "engagement_documents", sa.Column("udin_required", sa.Boolean(), nullable=False, server_default=sa.false()))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("udin_status", sa.String(length=30), nullable=False, server_default="not_required"))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("udin_number", sa.String(length=30), nullable=True))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("udin_date", sa.Date(), nullable=True))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("udin_document_date", sa.Date(), nullable=True))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("udin_document_type", sa.String(length=120), nullable=True))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("udin_financial_year", sa.String(length=9), nullable=True))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("udin_amount", sa.Numeric(14, 2), nullable=True))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("udin_generated_by_user_id", sa.Integer(), nullable=True))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("udin_verified_at_utc", sa.DateTime(timezone=True), nullable=True))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("udin_notes", sa.Text(), nullable=True))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("final_release_status", sa.String(length=30), nullable=False, server_default="draft"))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("released_by_user_id", sa.Integer(), nullable=True))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("released_at_utc", sa.DateTime(timezone=True), nullable=True))
    _add_column_if_missing(bind, "engagement_documents", sa.Column("release_notes", sa.Text(), nullable=True))

    _create_index_if_missing(bind, "ix_engagement_documents_udin_required", "engagement_documents", ["udin_required"])
    _create_index_if_missing(bind, "ix_engagement_documents_udin_status", "engagement_documents", ["udin_status"])
    _create_index_if_missing(bind, "ix_engagement_documents_udin_number", "engagement_documents", ["udin_number"])
    _create_index_if_missing(bind, "ix_engagement_documents_udin_date", "engagement_documents", ["udin_date"])
    _create_index_if_missing(bind, "ix_engagement_documents_udin_financial_year", "engagement_documents", ["udin_financial_year"])
    _create_index_if_missing(bind, "ix_engagement_documents_udin_generated_by_user_id", "engagement_documents", ["udin_generated_by_user_id"])
    _create_index_if_missing(bind, "ix_engagement_documents_final_release_status", "engagement_documents", ["final_release_status"])
    _create_index_if_missing(bind, "ix_engagement_documents_released_by_user_id", "engagement_documents", ["released_by_user_id"])

    # Lightweight FK creation is skipped intentionally in idempotent migration mode
    # because SQLite batch mode and existing production databases may differ. The
    # SQLAlchemy model still defines FK intent, and user IDs are set by application logic.


def downgrade() -> None:
    bind = op.get_bind()
    if "engagement_documents" not in inspect(bind).get_table_names():
        return
    for idx in [
        "ix_engagement_documents_released_by_user_id",
        "ix_engagement_documents_final_release_status",
        "ix_engagement_documents_udin_generated_by_user_id",
        "ix_engagement_documents_udin_financial_year",
        "ix_engagement_documents_udin_date",
        "ix_engagement_documents_udin_number",
        "ix_engagement_documents_udin_status",
        "ix_engagement_documents_udin_required",
    ]:
        if _has_index(bind, "engagement_documents", idx):
            op.drop_index(idx, table_name="engagement_documents")
    with op.batch_alter_table("engagement_documents") as batch:
        for col in [
            "release_notes", "released_at_utc", "released_by_user_id", "final_release_status",
            "udin_notes", "udin_verified_at_utc", "udin_generated_by_user_id", "udin_amount",
            "udin_financial_year", "udin_document_type", "udin_document_date", "udin_date",
            "udin_number", "udin_status", "udin_required",
        ]:
            if _has_column(bind, "engagement_documents", col):
                batch.drop_column(col)
