"""services phase s2: default task templates

Revision ID: 20260423_services_phase_s2_default_templates
Revises: 20260422_services_phase_s1
Create Date: 2026-04-23 19:30:00.000000
"""

from alembic import op
import sqlalchemy as sa

revision = "20260423_services_phase_s2_default_templates"
down_revision = "20260422_services_phase_s1"
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 upgrade():
    if not _has_table("service_default_task_templates"):
        op.create_table(
            "service_default_task_templates",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True, nullable=False),
            sa.Column("service_catalogue_id", sa.Integer(), nullable=False),
            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("is_mandatory", sa.Boolean(), nullable=False, server_default=sa.true()),
            sa.Column("requires_review", sa.Boolean(), nullable=False, server_default=sa.false()),
            sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()),
            sa.ForeignKeyConstraint(["service_catalogue_id"], ["service_catalogues.id"], ondelete="CASCADE"),
            sa.UniqueConstraint("service_catalogue_id", "sequence_no", name="uq_service_default_task_templates_sequence"),
        )
    if not _has_index("service_default_task_templates", "ix_service_default_task_templates_service_catalogue_id"):
        op.create_index("ix_service_default_task_templates_service_catalogue_id", "service_default_task_templates", ["service_catalogue_id"], unique=False)


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