# src/chitai/controllers/author.py

# Standard library
from typing import Annotated

# Third-party libraries
from litestar import Controller, get
from litestar.params import Dependency
from advanced_alchemy.extensions.litestar.providers import create_service_dependencies
from advanced_alchemy.service.pagination import OffsetPagination
from advanced_alchemy.service import FilterTypeT

# Local imports
from chitai.services import AuthorService
from chitai.schemas import AuthorRead
from chitai.services.filters.author import AuthorLibraryFilter


class AuthorController(Controller):
    """Controller for managing author information."""

    path = "/authors"
    dependencies = create_service_dependencies(
        AuthorService,
        key="author_service",
        filters={
            "id_filter": int,
            "pagination_type": "limit_offset",
            "sort_field": "name",
            "search": ["name"],
            "search_ignore_case": True,
        },
    )

    @get()
    async def list_authors(
        self,
        author_service: AuthorService,
        libraries: list[int] | None = None,
        filters: Annotated[list[FilterTypeT], Dependency(skip_validation=True)] = [],
    ) -> OffsetPagination[AuthorRead]:
        """
        List authors with filtering, pagination, and search.

        Supports searching by name and filtering by library. Results can be sorted
        and paginated using standard query parameters.

        Query Parameters:
            library_id: Optional library ID to filter authors. If None, returns all authors.
            id_filter: Filter by author ID (from create_filter_dependencies).
            sort_field: Field to sort by (default: 'name').
            search: Search term for author name field.
            search_ignore_case: Case-insensitive search (default: True).
            limit: Number of results per page (pagination).
            offset: Number of results to skip (pagination).

        Injected Dependencies:
            author_service: The author service for database operations.
            filters: Pre-constructed filters from dependencies.

        Returns:
            Paginated list of authors matching the criteria.
        """
        filters.append(AuthorLibraryFilter(libraries))

        authors, total = await author_service.list_and_count(*filters, uniquify=True)
        return author_service.to_schema(authors, total, filters, schema_type=AuthorRead)
