"""CRM 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_contacts(ctx: "RequestContext", query: str, limit: int) -> list[SearchHit]:
    from django.db.models import Q

    from simorgh.apps.crm.models import Contact

    if not ctx.tenant:
        return []

    qs = Contact.objects.filter(
        tenant_id=ctx.tenant.pk,
        deleted_at__isnull=True,
    ).filter(
        Q(name__icontains=query)
        | Q(phones__number__icontains=query)
        | Q(emails__address__icontains=query)
    ).distinct().order_by("name")[:limit]

    return [
        SearchHit(
            entity="crm.contact",
            id=str(c.public_id),
            title=c.name,
            subtitle=c.get_type_display(),
            url=f"/crm/contacts/{c.public_id}/",
            score=2.0 if query.lower() in c.name.lower() else 1.0,
        )
        for c in qs
    ]


def _search_leads(ctx: "RequestContext", query: str, limit: int) -> list[SearchHit]:
    from django.db.models import Q

    from simorgh.apps.crm.models import Lead

    if not ctx.tenant:
        return []

    qs = Lead.objects.filter(
        tenant_id=ctx.tenant.pk,
        deleted_at__isnull=True,
    ).filter(
        Q(title__icontains=query) | Q(notes__icontains=query)
    ).distinct().order_by("-created_at")[:limit]

    return [
        SearchHit(
            entity="crm.lead",
            id=str(lead.public_id),
            title=lead.title,
            subtitle=lead.get_status_display(),
            url=f"/crm/leads/{lead.public_id}/",
            score=2.0 if query.lower() in lead.title.lower() else 1.0,
        )
        for lead in qs
    ]


def _search_opportunities(ctx: "RequestContext", query: str, limit: int) -> list[SearchHit]:
    from django.db.models import Q

    from simorgh.apps.crm.models import Opportunity

    if not ctx.tenant:
        return []

    qs = Opportunity.objects.filter(
        tenant_id=ctx.tenant.pk,
        deleted_at__isnull=True,
    ).filter(
        Q(title__icontains=query)
    ).select_related("pipeline_stage").distinct().order_by("-created_at")[:limit]

    return [
        SearchHit(
            entity="crm.opportunity",
            id=str(opp.public_id),
            title=opp.title,
            subtitle=opp.pipeline_stage.name if opp.pipeline_stage_id else "",
            url=f"/crm/opportunities/{opp.public_id}/",
            score=2.0 if query.lower() in opp.title.lower() else 1.0,
        )
        for opp in qs
    ]


register_searchable(
    SearchableSpec(
        entity="crm.contact",
        label_key="crm.contact",
        search=_search_contacts,
    )
)

register_searchable(
    SearchableSpec(
        entity="crm.lead",
        label_key="crm.lead",
        search=_search_leads,
    )
)

register_searchable(
    SearchableSpec(
        entity="crm.opportunity",
        label_key="crm.opportunity",
        search=_search_opportunities,
    )
)
