# xll_kit/services/mixins/pagination_mixin.py
from sqlalchemy.orm import Session

from xll_kit.services.pagination import PaginationResult
from sqlalchemy import select, func


class PaginationMixin:
    def paginate(self, session: Session, query, skip: int = 0, limit: int = 20) -> PaginationResult:
        total_stmt = select(func.count()).select_from(query.subquery())
        total = session.scalar(total_stmt) or 0

        items_stmt = query.offset(skip).limit(limit)
        result = session.execute(items_stmt)
        items = result.scalars().all()

        page = (skip // limit) + 1 if limit else 1
        return PaginationResult(items=items, total=total, page=page, limit=limit)
