"""SME-Hub curated research search (PRD REPO-SP8)."""

from __future__ import annotations

from rest_framework import permissions
from rest_framework.generics import ListAPIView

from apps.repository.documents.audit_helper import action_access, audit_repository
from apps.repository.documents.models import Document
from apps.repository.documents.serializers import DocumentSerializer

_SMEHUB_ALLOWED_TYPES = {
    Document.DocumentType.PUBLICATION,
    Document.DocumentType.TECHNICAL_REPORT,
    Document.DocumentType.INNOVATION_DOCUMENT,
    Document.DocumentType.JOURNAL_ARTICLE,
}


class SmehubResearchSearchView(ListAPIView):
    """A curated subset of the Repository exposed to SME-Hub clients."""

    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = DocumentSerializer

    def get_queryset(self):
        qs = Document.objects.public().filter(document_type__in=_SMEHUB_ALLOWED_TYPES)
        q = (self.request.query_params.get("q") or "").strip()
        if q:
            qs = qs.filter(title__icontains=q)
        return qs[:50]

    def list(self, request, *args, **kwargs):
        # FRREP-INT010 — SME-Hub search events are explicitly named in the SRS as
        # auditable integration events.
        q = (request.query_params.get("q") or "").strip()
        audit_repository(
            actor=request.user if request.user.is_authenticated else None,
            action=action_access(),
            target_model="SmehubResearchSearch",
            object_id="",
            object_repr=f"SME-Hub research search: {q}"[:200],
            changes={"query": q, "source": "SME_HUB"},
            request=request,
        )
        return super().list(request, *args, **kwargs)


def deliver(outbox_row) -> None:
    """Outbox delivery stub — intentionally unused for SME-Hub (pull-based)."""
    pass
