"""WorkItem global search integration — unified search across work items."""

from __future__ import annotations

from typing import TYPE_CHECKING

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

if TYPE_CHECKING:
    from simorgh.core.context import RequestContext


def _search_workbox(ctx: RequestContext, query: str, limit: int) -> list[SearchHit]:
    from django.db.models import Q

    from simorgh.apps.workbox.models import WorkboxItem as WorkItem

    if not ctx.tenant or not ctx.user:
        return []

    qs = (
        WorkItem.objects.filter(
            tenant_id=ctx.tenant.pk,
            assigned_to_user_id=ctx.user.pk,
        )
        .filter(
            Q(title__icontains=query)
            | Q(summary__icontains=query)
            | Q(description__icontains=query)
            | Q(source_entity__icontains=query)
        )
        .distinct()
        .order_by("title")[:limit]
    )

    return [
        SearchHit(
            entity="workitem",
            id=str(item.public_id),
            title=item.title,
            subtitle=f"{item.get_item_type_display()} — {item.get_status_display()}",
            url=item.source_url or f"/workitems/{item.public_id}/",
            score=2.0 if query.lower() in item.title.lower() else 1.0,
        )
        for item in qs
    ]


register_searchable(
    SearchableSpec(
        entity="workitem",
        label_key="workitem.search_label",
        search=_search_workbox,
    )
)

