"""add engagement type to services and engagements

Revision ID: 20260501_services_engagement_type
Revises: 20260429_engagement_year_locking
Create Date: 2026-05-01
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "20260501_services_engagement_type"
down_revision: Union[str, None] = "20260429_engagement_year_locking"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def _has_column(table_name: str, column_name: str) -> bool:
    bind = op.get_bind()
    insp = sa.inspect(bind)
    return any(c["name"] == column_name for c in insp.get_columns(table_name))


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


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


def upgrade() -> None:
    if not _has_column("service_catalogues", "engagement_type"):
        op.add_column(
            "service_catalogues",
            sa.Column("engagement_type", sa.String(length=20), nullable=False, server_default="non_audit"),
        )

    if not _has_column("client_service_subscriptions", "engagement_type"):
        op.add_column(
            "client_service_subscriptions",
            sa.Column("engagement_type", sa.String(length=20), nullable=False, server_default="non_audit"),
        )

    # Backfill existing engagement records from their service catalogue classification.
    bind = op.get_bind()
    bind.execute(sa.text("""
        UPDATE client_service_subscriptions
        SET engagement_type = COALESCE(
            (
                SELECT service_catalogues.engagement_type
                FROM service_catalogues
                WHERE service_catalogues.id = client_service_subscriptions.service_catalogue_id
            ),
            'non_audit'
        )
        WHERE engagement_type IS NULL OR engagement_type = ''
    """))

    _create_index_if_missing("service_catalogues", "ix_service_catalogues_engagement_type", ["engagement_type"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_engagement_type", ["engagement_type"])


def downgrade() -> None:
    if _has_index("client_service_subscriptions", "ix_client_service_subscriptions_engagement_type"):
        op.drop_index("ix_client_service_subscriptions_engagement_type", table_name="client_service_subscriptions")
    if _has_index("service_catalogues", "ix_service_catalogues_engagement_type"):
        op.drop_index("ix_service_catalogues_engagement_type", table_name="service_catalogues")
    if _has_column("client_service_subscriptions", "engagement_type"):
        op.drop_column("client_service_subscriptions", "engagement_type")
    if _has_column("service_catalogues", "engagement_type"):
        op.drop_column("service_catalogues", "engagement_type")
