from alembic import op
import sqlalchemy as sa

revision = "20260420_services_catalogue_firm_toggle"
down_revision = "20260420_services_catalogue_and_firm_templates"
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) -> None:
    if not _has_index(table_name, index_name):
        op.create_index(index_name, table_name, columns, unique=unique)


def upgrade():
    if not _has_table("firm_service_selections"):
        op.create_table(
            "firm_service_selections",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True, nullable=False),
            sa.Column("tenant_id", sa.Integer(), nullable=False),
            sa.Column("service_catalogue_id", sa.Integer(), nullable=False),
            sa.Column("is_enabled", sa.Boolean(), nullable=False, server_default=sa.true()),
            sa.Column("default_branch_id", sa.Integer(), nullable=True),
            sa.Column("activated_by_user_id", sa.Integer(), nullable=True),
            sa.Column("updated_by_user_id", sa.Integer(), nullable=True),
            sa.Column("activated_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(["service_catalogue_id"], ["service_catalogues.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["default_branch_id"], ["branches.id"]),
            sa.ForeignKeyConstraint(["activated_by_user_id"], ["users.id"]),
            sa.ForeignKeyConstraint(["updated_by_user_id"], ["users.id"]),
            sa.UniqueConstraint("tenant_id", "service_catalogue_id", name="uq_firm_service_selections_tenant_catalogue"),
        )

    _create_index_if_missing(
        "firm_service_selections",
        "ix_firm_service_selections_tenant_id",
        ["tenant_id"],
    )
    _create_index_if_missing(
        "firm_service_selections",
        "ix_firm_service_selections_service_catalogue_id",
        ["service_catalogue_id"],
    )
    _create_index_if_missing(
        "firm_service_selections",
        "ix_firm_service_selections_default_branch_id",
        ["default_branch_id"],
    )

    conn = op.get_bind()

    if _has_table("services") and _has_table("service_catalogues"):
        conn.execute(sa.text(
            """
            INSERT INTO firm_service_selections (
                tenant_id,
                service_catalogue_id,
                is_enabled,
                default_branch_id,
                activated_by_user_id,
                updated_by_user_id,
                activated_at_utc,
                updated_at_utc
            )
            SELECT
                s.tenant_id,
                sc.id,
                (MAX(CASE WHEN s.is_active THEN 1 ELSE 0 END) = 1) AS is_enabled,
                MIN(s.branch_id) AS default_branch_id,
                MIN(s.created_by_user_id) AS activated_by_user_id,
                MIN(s.updated_by_user_id) AS updated_by_user_id,
                MIN(s.created_at_utc) AS activated_at_utc,
                MAX(s.updated_at_utc) AS updated_at_utc
            FROM services s
            JOIN service_catalogues sc
              ON sc.service_code = s.service_code
            WHERE NOT EXISTS (
                SELECT 1
                FROM firm_service_selections fss
                WHERE fss.tenant_id = s.tenant_id
                  AND fss.service_catalogue_id = sc.id
            )
            GROUP BY s.tenant_id, sc.id
            """
        ))


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