"""Shared fixtures for willian-search tests."""

from __future__ import annotations

import pytest

from search.backends.memory import MemoryBackend
from search.config import close_search, set_search
from search.models import IndexConfig
from search.service import SearchService


@pytest.fixture()
async def memory_backend() -> MemoryBackend:
    """Provide a fresh in-memory backend."""
    backend = MemoryBackend()
    set_search(backend)
    yield backend
    await backend.close()


@pytest.fixture()
async def search_service(memory_backend: MemoryBackend) -> SearchService:
    """Provide a SearchService backed by the in-memory backend."""
    return SearchService(memory_backend)


@pytest.fixture()
async def articles_index(memory_backend: MemoryBackend) -> MemoryBackend:
    """Create an 'articles' index with sample config and return the backend."""
    config = IndexConfig(
        name="articles",
        searchable_fields=["title", "body"],
        filterable_fields=["category", "status"],
        sortable_fields=["title", "created_at"],
    )
    await memory_backend.create_index(config)
    return memory_backend


@pytest.fixture(autouse=True)
async def _cleanup_global_search():
    """Ensure global search state is cleaned up after each test."""
    yield
    try:
        await close_search()
    except RuntimeError:
        pass
