from typing import Optional
from dataclasses import dataclass

from advanced_alchemy.filters import (
    StatementTypeT,
    StatementFilter,
    ModelT,
)

from chitai.database import models as m


@dataclass
class PublisherLibraryFilter(StatementFilter):
    """Filter authors by library_id - returns publishers with at least one book in the library."""

    libraries: Optional[list[int]] = None

    def append_to_statement(
        self, statement: StatementTypeT, model: type[ModelT], *args, **kwargs
    ) -> StatementTypeT:
        if self.libraries:
            statement = statement.where(
                m.Book.publisher_id == m.Publisher.id,
                m.Book.library_id.in_(self.libraries),
            )

        return super().append_to_statement(statement, model, *args, **kwargs)
