import httpx
import msgspec

from csirtmu.external_services.outline.structs import OutlineResult
from csirtmu.self_service_backend.config import OutlineConfig


class OutlineClient:
    def __init__(self, config: OutlineConfig) -> None:
        self.config = config
        self.client = httpx.Client

    def search_documents(self, query: str) -> list[OutlineResult]:
        if not query:
            return []
        with self.client() as client:
            response = client.post(
                self.config.documents_search_url,
                headers=self.config.auth_headers | {"Content-Type": "application/json"},
                json={"query": query},
            )
            data = response.json()["data"]
            for item in data:
                item["document"]["url"] = self.config.link_url
            return msgspec.convert(data, type=list[OutlineResult])
