"""Time Tracking global search integration."""

from __future__ import annotations

from typing import TYPE_CHECKING

from simorgh.core.search import SearchHit, SearchableSpec, register_searchable

if TYPE_CHECKING:
    from simorgh.core.context import RequestContext


def _search_entries(ctx: "RequestContext", query: str, limit: int) -> list[SearchHit]:
    from django.db.models import Q
    from simorgh.apps.time_tracking.models import TimeEntry

    if not ctx.tenant:
        return []

    qs = (
        TimeEntry.objects
        .filter(tenant_id=ctx.tenant.pk)
        .filter(Q(description__icontains=query))
        .select_related("project", "user")[:limit]
    )
    return [
        SearchHit(
            entity="time_tracking.entry",
            id=str(e.public_id),
            title=f"{e.hours}h on {e.project.name} ({e.date})",
            subtitle=e.description[:80] if e.description else "",
            url=f"/time/{e.public_id}",
            score=1.0,
        )
        for e in qs
    ]


register_searchable(
    SearchableSpec(
        entity="time_tracking.entry",
        label_key="time_tracking.entry",
        search=_search_entries,
    )
)
