"""Catalog Engine — global search registration."""

from __future__ import annotations

from simorgh.core.search import SearchableSpec, SearchHit, register_searchable


def _search_catalog(ctx, query: str) -> list[SearchHit]:  # type: ignore[type-arg]
    from django.db.models import Q

    from simorgh.apps.catalog.models import CatalogItem, CatalogItemStatus

    if not ctx.tenant_id:
        return []

    qs = CatalogItem.objects.filter(
        tenant_id=ctx.tenant_id,
        status=CatalogItemStatus.PUBLISHED,
    ).select_related("category")[:20]

    qs = qs.filter(
        Q(name__icontains=query)
        | Q(description__icontains=query)
        | Q(short_description__icontains=query)
        | Q(category__name__icontains=query)
    )

    results: list[SearchHit] = []
    for item in qs:
        ctype = item.get_catalog_type_display() if hasattr(item, "get_catalog_type_display") else item.catalog_type
        cat = item.category.name if item.category_id else ""
        results.append(
            SearchHit(
                entity_type="catalog.item",
                entity_id=str(item.public_id),
                title=item.name,
                subtitle=f"{ctype} · {cat}".strip(" ·"),
                url=f"/catalog/items/{item.public_id}",
                score=1.0,
            )
        )
    return results


register_searchable(
    SearchableSpec(
        entity="catalog.item",
        label_key="catalog.item",
        search=_search_catalog,
    )
)
