"""Phase 8A - task level documents and task template uploads

Revision ID: 20260615_phase_8a_task_docs
Revises: 20260614_phase_7t9_ssl_automation
Create Date: 2026-06-02
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "20260615_phase_8a_task_docs"
down_revision = "20260614_phase_7t9_ssl_automation"
branch_labels = None
depends_on = None


def _inspect(bind):
    return sa.inspect(bind)


def _has_table(bind, table_name: str) -> bool:
    return _inspect(bind).has_table(table_name)


def _has_column(bind, table_name: str, column_name: str) -> bool:
    if not _has_table(bind, table_name):
        return False
    return column_name in {col["name"] for col in _inspect(bind).get_columns(table_name)}


def _has_index(bind, table_name: str, index_name: str) -> bool:
    if not _has_table(bind, table_name):
        return False
    return index_name in {ix["name"] for ix in _inspect(bind).get_indexes(table_name)}


def upgrade() -> None:
    bind = op.get_bind()

    if not _has_table(bind, "firm_task_document_requirements"):
        op.create_table(
            "firm_task_document_requirements",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
            sa.Column("tenant_id", sa.Integer(), nullable=False),
            sa.Column("service_catalogue_id", sa.Integer(), nullable=False),
            sa.Column("firm_task_template_id", sa.Integer(), nullable=False),
            sa.Column("document_name", sa.String(length=200), nullable=False),
            sa.Column("document_type", sa.String(length=80), nullable=False, server_default="GENERAL"),
            sa.Column("is_mandatory", sa.Boolean(), nullable=False, server_default=sa.true()),
            sa.Column("allowed_file_types", sa.String(length=255), nullable=True),
            sa.Column("instructions", sa.Text(), nullable=True),
            sa.Column("sort_order", sa.Integer(), nullable=False, server_default="100"),
            sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.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, server_default=sa.func.now()),
            sa.Column("updated_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
            sa.ForeignKeyConstraint(["tenant_id"], ["tenants.id"], name="fk_firm_task_doc_req_tenant_id", ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["service_catalogue_id"], ["service_catalogues.id"], name="fk_firm_task_doc_req_service_catalogue_id", ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["firm_task_template_id"], ["firm_service_task_templates.id"], name="fk_firm_task_doc_req_firm_task_template_id", ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["created_by_user_id"], ["users.id"], name="fk_firm_task_doc_req_created_by_user_id"),
            sa.ForeignKeyConstraint(["updated_by_user_id"], ["users.id"], name="fk_firm_task_doc_req_updated_by_user_id"),
            sa.UniqueConstraint("tenant_id", "firm_task_template_id", "document_name", name="uq_firm_task_document_requirements_name"),
        )
    if not _has_index(bind, "firm_task_document_requirements", "ix_firm_task_document_requirements_tenant_id"):
        op.create_index("ix_firm_task_document_requirements_tenant_id", "firm_task_document_requirements", ["tenant_id"])
    if not _has_index(bind, "firm_task_document_requirements", "ix_firm_task_document_requirements_service_catalogue_id"):
        op.create_index("ix_firm_task_document_requirements_service_catalogue_id", "firm_task_document_requirements", ["service_catalogue_id"])
    if not _has_index(bind, "firm_task_document_requirements", "ix_firm_task_document_requirements_firm_task_template_id"):
        op.create_index("ix_firm_task_document_requirements_firm_task_template_id", "firm_task_document_requirements", ["firm_task_template_id"])
    if not _has_index(bind, "firm_task_document_requirements", "ix_firm_task_document_requirements_document_type"):
        op.create_index("ix_firm_task_document_requirements_document_type", "firm_task_document_requirements", ["document_type"])

    if not _has_table(bind, "firm_task_document_templates"):
        op.create_table(
            "firm_task_document_templates",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
            sa.Column("tenant_id", sa.Integer(), nullable=False),
            sa.Column("service_catalogue_id", sa.Integer(), nullable=False),
            sa.Column("firm_task_template_id", sa.Integer(), nullable=False),
            sa.Column("template_name", sa.String(length=200), nullable=False),
            sa.Column("template_category", sa.String(length=100), nullable=True),
            sa.Column("description", sa.Text(), nullable=True),
            sa.Column("original_filename", sa.String(length=255), nullable=False),
            sa.Column("stored_filename", sa.String(length=255), nullable=False),
            sa.Column("content_type", sa.String(length=150), nullable=True),
            sa.Column("file_size_bytes", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("local_relative_path", sa.String(length=1000), nullable=False),
            sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()),
            sa.Column("uploaded_by_user_id", sa.Integer(), nullable=True),
            sa.Column("uploaded_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
            sa.ForeignKeyConstraint(["tenant_id"], ["tenants.id"], name="fk_firm_task_doc_tpl_tenant_id", ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["service_catalogue_id"], ["service_catalogues.id"], name="fk_firm_task_doc_tpl_service_catalogue_id", ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["firm_task_template_id"], ["firm_service_task_templates.id"], name="fk_firm_task_doc_tpl_firm_task_template_id", ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["uploaded_by_user_id"], ["users.id"], name="fk_firm_task_doc_tpl_uploaded_by_user_id"),
        )
    if not _has_index(bind, "firm_task_document_templates", "ix_firm_task_document_templates_tenant_id"):
        op.create_index("ix_firm_task_document_templates_tenant_id", "firm_task_document_templates", ["tenant_id"])
    if not _has_index(bind, "firm_task_document_templates", "ix_firm_task_document_templates_service_catalogue_id"):
        op.create_index("ix_firm_task_document_templates_service_catalogue_id", "firm_task_document_templates", ["service_catalogue_id"])
    if not _has_index(bind, "firm_task_document_templates", "ix_firm_task_document_templates_firm_task_template_id"):
        op.create_index("ix_firm_task_document_templates_firm_task_template_id", "firm_task_document_templates", ["firm_task_template_id"])
    if not _has_index(bind, "firm_task_document_templates", "ix_firm_task_document_templates_template_category"):
        op.create_index("ix_firm_task_document_templates_template_category", "firm_task_document_templates", ["template_category"])
    if not _has_index(bind, "firm_task_document_templates", "ix_firm_task_document_templates_is_active"):
        op.create_index("ix_firm_task_document_templates_is_active", "firm_task_document_templates", ["is_active"])

    # SQLite-safe: add nullable columns only. Do not create batch foreign-key constraints here.
    # SQLAlchemy relationships in the app still work through these *_id columns.
    if _has_table(bind, "engagement_documents"):
        with op.batch_alter_table("engagement_documents") as batch:
            if not _has_column(bind, "engagement_documents", "task_instance_id"):
                batch.add_column(sa.Column("task_instance_id", sa.Integer(), nullable=True))
            if not _has_column(bind, "engagement_documents", "document_requirement_id"):
                batch.add_column(sa.Column("document_requirement_id", sa.Integer(), nullable=True))

        if not _has_index(bind, "engagement_documents", "ix_engagement_documents_task_instance_id"):
            op.create_index("ix_engagement_documents_task_instance_id", "engagement_documents", ["task_instance_id"])
        if not _has_index(bind, "engagement_documents", "ix_engagement_documents_document_requirement_id"):
            op.create_index("ix_engagement_documents_document_requirement_id", "engagement_documents", ["document_requirement_id"])


def downgrade() -> None:
    bind = op.get_bind()

    if _has_table(bind, "engagement_documents"):
        if _has_index(bind, "engagement_documents", "ix_engagement_documents_document_requirement_id"):
            op.drop_index("ix_engagement_documents_document_requirement_id", table_name="engagement_documents")
        if _has_index(bind, "engagement_documents", "ix_engagement_documents_task_instance_id"):
            op.drop_index("ix_engagement_documents_task_instance_id", table_name="engagement_documents")
        with op.batch_alter_table("engagement_documents") as batch:
            if _has_column(bind, "engagement_documents", "document_requirement_id"):
                batch.drop_column("document_requirement_id")
            if _has_column(bind, "engagement_documents", "task_instance_id"):
                batch.drop_column("task_instance_id")

    if _has_table(bind, "firm_task_document_templates"):
        op.drop_table("firm_task_document_templates")
    if _has_table(bind, "firm_task_document_requirements"):
        op.drop_table("firm_task_document_requirements")
