"""Helpdesk global search integration.

Registers the ``helpdesk.ticket`` entity with the platform's global search
registry so the workspace-level ⌘K search bar can find tickets.

Registration happens at app startup via ``HelpdeskConfig.ready()`` or
by importing this module.
"""

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


# ---------------------------------------------------------------------------
# Ticket search adapter
# ---------------------------------------------------------------------------

def _search_tickets(ctx: "RequestContext", query: str, limit: int) -> list[SearchHit]:
    """Full-text search across tickets visible to the current actor."""
    from django.db.models import Q

    from simorgh.apps.helpdesk.models import Ticket
    from simorgh.apps.helpdesk.permissions import PERM_TICKET_CHANGE

    if not ctx.tenant:
        return []

    qs = Ticket.objects.filter(tenant_id=ctx.tenant.pk).select_related("queue")

    # Portal users (non-agents) only see their own tickets.
    is_agent = ctx.is_superuser or PERM_TICKET_CHANGE in (ctx.permissions or set())
    if not is_agent and ctx.actor:
        qs = qs.filter(requester=ctx.actor)

    # Text match: subject, description, requester email/name.
    qs = qs.filter(
        Q(subject__icontains=query)
        | Q(description__icontains=query)
        | Q(requester_email__icontains=query)
        | Q(requester_name__icontains=query)
    ).order_by("-created_at")[:limit]

    hits = []
    for ticket in qs:
        # Simple relevance: subject matches score higher.
        score = 1.0
        if query.lower() in ticket.subject.lower():
            score = 2.0

        hits.append(
            SearchHit(
                entity="helpdesk.ticket",
                id=str(ticket.public_id),
                title=ticket.subject,
                subtitle=f"#{ticket.pk} · {ticket.status} · {ticket.queue.name}",
                url=f"/helpdesk/tickets/{ticket.public_id}/",
                icon="ticket",
                score=score,
                extra={
                    "status": ticket.status,
                    "priority": ticket.priority,
                    "queue_id": ticket.queue_id,
                },
            )
        )

    return hits


# ---------------------------------------------------------------------------
# Queue search adapter
# ---------------------------------------------------------------------------

def _search_queues(ctx: "RequestContext", query: str, limit: int) -> list[SearchHit]:
    from simorgh.apps.helpdesk.models import Queue
    from simorgh.apps.helpdesk.permissions import PERM_QUEUE_MANAGE

    if not ctx.tenant:
        return []

    # Only agents / supervisors should see queues in global search.
    if not ctx.is_superuser and PERM_QUEUE_MANAGE not in (ctx.permissions or set()):
        return []

    qs = Queue.objects.filter(
        tenant_id=ctx.tenant.pk,
        is_active=True,
        name__icontains=query,
    )[:limit]

    return [
        SearchHit(
            entity="helpdesk.queue",
            id=str(q.public_id),
            title=q.name,
            subtitle=q.description[:80] if q.description else "",
            url=f"/helpdesk/queues/{q.public_id}/",
            icon="inbox",
            score=1.0,
        )
        for q in qs
    ]


# ---------------------------------------------------------------------------
# Registration
# ---------------------------------------------------------------------------

TICKET_SEARCHABLE = register_searchable(
    SearchableSpec(
        entity="helpdesk.ticket",
        label_key="helpdesk.search.ticket",
        search=_search_tickets,
        permission="helpdesk.view_ticket",
        description="Support tickets",
    )
)

QUEUE_SEARCHABLE = register_searchable(
    SearchableSpec(
        entity="helpdesk.queue",
        label_key="helpdesk.search.queue",
        search=_search_queues,
        permission="helpdesk.view_queue",
        description="Support queues",
    )
)
