"""S4.3/S4.4 service execution task instances

Revision ID: 20260426_service_execution_tasks
Revises: 20260425_client_service_subscriptions
Create Date: 2026-04-26 20:00:00.000000
"""

from alembic import op
import sqlalchemy as sa

revision = "20260426_service_execution_tasks"
down_revision = "20260425_client_service_subscriptions"
branch_labels = None
depends_on = None


def _inspector():
    return sa.inspect(op.get_bind())


def _has_table(name: str) -> bool:
    return name in _inspector().get_table_names()


def _has_index(table_name: str, index_name: str) -> bool:
    try:
        indexes = _inspector().get_indexes(table_name)
    except Exception:
        return False
    return any(ix.get("name") == index_name for ix in indexes)


def _create_index_if_missing(table_name: str, index_name: str, columns, unique: bool = False):
    if not _has_index(table_name, index_name):
        op.create_index(index_name, table_name, columns, unique=unique)


def upgrade():
    if not _has_table("client_service_task_instances"):
        op.create_table(
            "client_service_task_instances",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True, nullable=False),
            sa.Column("tenant_id", sa.Integer(), nullable=False),
            sa.Column("branch_id", sa.Integer(), nullable=True),
            sa.Column("subscription_id", sa.Integer(), nullable=False),
            sa.Column("client_id", sa.Integer(), nullable=False),
            sa.Column("service_catalogue_id", sa.Integer(), nullable=False),
            sa.Column("firm_task_template_id", sa.Integer(), nullable=True),
            sa.Column("task_name", sa.String(length=200), nullable=False),
            sa.Column("description", sa.Text(), nullable=True),
            sa.Column("sequence_no", sa.Integer(), nullable=False, server_default="1"),
            sa.Column("default_role_name", sa.String(length=100), nullable=True),
            sa.Column("assigned_to_user_id", sa.Integer(), nullable=True),
            sa.Column("status", sa.String(length=30), nullable=False, server_default="pending"),
            sa.Column("priority", sa.String(length=20), nullable=False, server_default="normal"),
            sa.Column("remarks", sa.Text(), nullable=True),
            sa.Column("started_at_utc", sa.DateTime(), nullable=True),
            sa.Column("completed_at_utc", sa.DateTime(), nullable=True),
            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(), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
            sa.Column("updated_at_utc", sa.DateTime(), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
            sa.ForeignKeyConstraint(["tenant_id"], ["tenants.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["branch_id"], ["branches.id"]),
            sa.ForeignKeyConstraint(["subscription_id"], ["client_service_subscriptions.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["client_id"], ["clients.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["service_catalogue_id"], ["service_catalogues.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["firm_task_template_id"], ["firm_service_task_templates.id"], ondelete="SET NULL"),
            sa.ForeignKeyConstraint(["assigned_to_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["created_by_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["updated_by_user_id"], ["users.id"]),
            sa.UniqueConstraint("subscription_id", "firm_task_template_id", name="uq_client_service_task_subscription_template"),
        )

    _create_index_if_missing("client_service_task_instances", "ix_client_service_task_instances_tenant_id", ["tenant_id"])
    _create_index_if_missing("client_service_task_instances", "ix_client_service_task_instances_branch_id", ["branch_id"])
    _create_index_if_missing("client_service_task_instances", "ix_client_service_task_instances_subscription_id", ["subscription_id"])
    _create_index_if_missing("client_service_task_instances", "ix_client_service_task_instances_client_id", ["client_id"])
    _create_index_if_missing("client_service_task_instances", "ix_client_service_task_instances_service_catalogue_id", ["service_catalogue_id"])
    _create_index_if_missing("client_service_task_instances", "ix_client_service_task_instances_assigned_to_user_id", ["assigned_to_user_id"])
    _create_index_if_missing("client_service_task_instances", "ix_client_service_task_instances_status", ["status"])
    _create_index_if_missing("client_service_task_instances", "ix_client_service_task_instances_is_active", ["is_active"])


def downgrade():
    if _has_table("client_service_task_instances"):
        op.drop_table("client_service_task_instances")
