"""engagement year columns and locking

Revision ID: 20260429_engagement_year_locking
Revises: 20260426_service_execution_tasks
Create Date: 2026-04-29
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "20260429_engagement_year_locking"
down_revision: Union[str, None] = "20260426_service_execution_tasks"
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], 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_column("client_service_subscriptions", "financial_year"):
        op.add_column("client_service_subscriptions", sa.Column("financial_year", sa.String(length=9), nullable=False, server_default="2025-26"))
    if not _has_column("client_service_subscriptions", "assessment_year"):
        op.add_column("client_service_subscriptions", sa.Column("assessment_year", sa.String(length=9), nullable=True))
    if not _has_column("client_service_subscriptions", "is_locked"):
        op.add_column("client_service_subscriptions", sa.Column("is_locked", sa.Boolean(), nullable=False, server_default=sa.false()))
    if not _has_column("client_service_subscriptions", "locked_at_utc"):
        op.add_column("client_service_subscriptions", sa.Column("locked_at_utc", sa.DateTime(timezone=True), nullable=True))
    if not _has_column("client_service_subscriptions", "locked_by_user_id"):
        op.add_column("client_service_subscriptions", sa.Column("locked_by_user_id", sa.Integer(), nullable=True))

    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_financial_year", ["financial_year"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_assessment_year", ["assessment_year"])
    _create_index_if_missing("client_service_subscriptions", "ix_client_service_subscriptions_is_locked", ["is_locked"])

    if not _has_column("client_service_task_instances", "financial_year"):
        op.add_column("client_service_task_instances", sa.Column("financial_year", sa.String(length=9), nullable=False, server_default="2025-26"))
    if not _has_column("client_service_task_instances", "assessment_year"):
        op.add_column("client_service_task_instances", sa.Column("assessment_year", sa.String(length=9), nullable=True))
    if not _has_column("client_service_task_instances", "is_locked"):
        op.add_column("client_service_task_instances", sa.Column("is_locked", sa.Boolean(), nullable=False, server_default=sa.false()))
    if not _has_column("client_service_task_instances", "locked_at_utc"):
        op.add_column("client_service_task_instances", sa.Column("locked_at_utc", sa.DateTime(timezone=True), nullable=True))
    if not _has_column("client_service_task_instances", "locked_by_user_id"):
        op.add_column("client_service_task_instances", sa.Column("locked_by_user_id", sa.Integer(), nullable=True))

    _create_index_if_missing("client_service_task_instances", "ix_client_service_task_instances_financial_year", ["financial_year"])
    _create_index_if_missing("client_service_task_instances", "ix_client_service_task_instances_assessment_year", ["assessment_year"])
    _create_index_if_missing("client_service_task_instances", "ix_client_service_task_instances_is_locked", ["is_locked"])

    # SQLite/PostgreSQL compatible replacement of uniqueness to include financial_year.
    with op.batch_alter_table("client_service_subscriptions") as batch_op:
        try:
            batch_op.drop_constraint("uq_client_service_subscription_tenant_client_service", type_="unique")
        except Exception:
            pass
        try:
            batch_op.create_unique_constraint(
                "uq_client_service_subscription_tenant_client_service_year",
                ["tenant_id", "client_id", "service_catalogue_id", "financial_year"],
            )
        except Exception:
            pass

    with op.batch_alter_table("client_service_task_instances") as batch_op:
        try:
            batch_op.drop_constraint("uq_client_service_task_subscription_template", type_="unique")
        except Exception:
            pass
        try:
            batch_op.create_unique_constraint(
                "uq_client_service_task_subscription_template_year",
                ["subscription_id", "firm_task_template_id", "financial_year"],
            )
        except Exception:
            pass


def downgrade() -> None:
    pass
