from typing import Optional
from dataclasses import dataclass

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

from chitai.database import models as m
from sqlalchemy import select


@dataclass
class TagLibraryFilter(StatementFilter):
    """Filter tags by library_id - returns tags 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.Tag.id.in_(
                    select(m.BookTagLink.tag_id)
                    .join(m.Book)
                    .where(m.Book.library_id.in_(self.libraries))
                )
            )
        return super().append_to_statement(statement, model, *args, **kwargs)
