"""Calendar 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_events(ctx: "RequestContext", query: str, limit: int) -> list[SearchHit]:
    from django.db.models import Q

    from simorgh.apps.calendar.models import CalendarEvent

    if not ctx.tenant:
        return []

    user = ctx.actor
    if not user:
        return []

    qs = CalendarEvent.objects.filter(
        tenant_id=ctx.tenant.pk,
    ).filter(
        Q(title__icontains=query)
        | Q(location__icontains=query)
        | Q(owner__email__icontains=query)
    ).filter(
        Q(owner_id=user.pk) | Q(attendees__user_id=user.pk)
    ).distinct().select_related("owner").order_by("start_dt")[:limit]

    return [
        SearchHit(
            entity="calendar.event",
            id=str(e.public_id),
            title=e.title,
            subtitle=e.location or e.start_dt.strftime("%Y-%m-%d %H:%M"),
            url=f"/calendar/events/{e.public_id}/",
            score=2.0 if query.lower() in e.title.lower() else 1.0,
        )
        for e in qs
    ]


register_searchable(
    SearchableSpec(
        entity="calendar.event",
        label_key="calendar.event",
        search=_search_events,
    )
)
