"""split services into system catalogue and firm task templates

Revision ID: 20260420_services_catalogue_and_firm_templates
Revises: 20260419_client_portal_user_link
Create Date: 2026-04-20 18:00:00.000000
"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa

revision: str = "20260420_services_catalogue_and_firm_templates"
down_revision: Union[str, None] = "20260419_client_portal_user_link"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = 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: 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_table("service_catalogues"):
        op.create_table(
            "service_catalogues",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True, nullable=False),
            sa.Column("service_code", sa.String(length=50), nullable=False),
            sa.Column("service_name", sa.String(length=200), nullable=False),
            sa.Column("category", sa.String(length=100), nullable=True),
            sa.Column("description", sa.Text(), nullable=True),
            sa.Column("recurrence_type", sa.String(length=50), nullable=True),
            sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()),
            sa.Column("is_client_requestable", sa.Boolean(), nullable=False, server_default=sa.false()),
            sa.Column("is_consultant_requestable", sa.Boolean(), nullable=False, server_default=sa.false()),
            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),
            sa.Column("updated_at_utc", sa.DateTime(), nullable=False),
            sa.ForeignKeyConstraint(["created_by_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["updated_by_user_id"], ["users.id"]),
            sa.UniqueConstraint("service_code", name="uq_service_catalogues_code"),
        )
    _create_index_if_missing("service_catalogues", "ix_service_catalogues_service_code", ["service_code"])
    _create_index_if_missing("service_catalogues", "ix_service_catalogues_service_name", ["service_name"])
    _create_index_if_missing("service_catalogues", "ix_service_catalogues_category", ["category"])

    if not _has_table("firm_service_task_templates"):
        op.create_table(
            "firm_service_task_templates",
            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("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),
            sa.Column("default_role_name", sa.String(length=100), nullable=True),
            sa.Column("sla_days", sa.Integer(), 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.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),
            sa.Column("updated_at_utc", sa.DateTime(), nullable=False),
            sa.ForeignKeyConstraint(["tenant_id"], ["tenants.id"]),
            sa.ForeignKeyConstraint(["branch_id"], ["branches.id"]),
            sa.ForeignKeyConstraint(["service_catalogue_id"], ["service_catalogues.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["created_by_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["updated_by_user_id"], ["users.id"]),
            sa.UniqueConstraint("tenant_id", "service_catalogue_id", "sequence_no", name="uq_firm_service_task_sequence"),
        )
    _create_index_if_missing("firm_service_task_templates", "ix_firm_service_task_templates_tenant_id", ["tenant_id"])
    _create_index_if_missing("firm_service_task_templates", "ix_firm_service_task_templates_branch_id", ["branch_id"])
    _create_index_if_missing("firm_service_task_templates", "ix_firm_service_task_templates_service_catalogue_id", ["service_catalogue_id"])

    bind = op.get_bind()
    if _has_table("services"):
        bind.execute(sa.text(
            """
            INSERT INTO service_catalogues (
                service_code, service_name, category, description, recurrence_type,
                is_active, is_client_requestable, is_consultant_requestable,
                created_by_user_id, updated_by_user_id, created_at_utc, updated_at_utc
            )
            SELECT
                s.service_code,
                MIN(s.service_name) AS service_name,
                MIN(s.category) AS category,
                MIN(s.description) AS description,
                NULL AS recurrence_type,
                (MAX(CASE WHEN s.is_active THEN 1 ELSE 0 END) = 1) AS is_active,
                (MAX(CASE WHEN s.is_client_requestable THEN 1 ELSE 0 END) = 1) AS is_client_requestable,
                (MAX(CASE WHEN s.is_consultant_requestable THEN 1 ELSE 0 END) = 1) AS is_consultant_requestable,
                MIN(s.created_by_user_id) AS created_by_user_id,
                MIN(s.updated_by_user_id) AS updated_by_user_id,
                MIN(s.created_at_utc) AS created_at_utc,
                MAX(s.updated_at_utc) AS updated_at_utc
            FROM services s
            WHERE NOT EXISTS (
                SELECT 1 FROM service_catalogues sc WHERE sc.service_code = s.service_code
            )
            GROUP BY s.service_code
            """
        ))

    if _has_table("services") and _has_table("service_task_templates"):
        bind.execute(sa.text(
            """
            INSERT INTO firm_service_task_templates (
                tenant_id, branch_id, service_catalogue_id,
                task_name, description, sequence_no, default_role_name, sla_days,
                is_mandatory, requires_review, is_active,
                created_by_user_id, updated_by_user_id, created_at_utc, updated_at_utc
            )
            SELECT
                s.tenant_id,
                s.branch_id,
                sc.id,
                st.task_name,
                st.description,
                st.sequence_no,
                st.default_role_name,
                NULL AS sla_days,
                st.is_mandatory,
                st.requires_review,
                st.is_active,
                st.created_by_user_id,
                st.updated_by_user_id,
                st.created_at_utc,
                st.updated_at_utc
            FROM service_task_templates st
            JOIN services s ON s.id = st.service_id
            JOIN service_catalogues sc ON sc.service_code = s.service_code
            WHERE NOT EXISTS (
                SELECT 1 FROM firm_service_task_templates ft
                WHERE ft.tenant_id = s.tenant_id
                  AND ft.service_catalogue_id = sc.id
                  AND ft.sequence_no = st.sequence_no
            )
            """
        ))


def downgrade() -> None:
    pass
