"""Category repository — typed CRUD for hierarchical categories."""
from __future__ import annotations

import logging
from typing import Any

from repo_core import BaseRepository
from repo_core.domains.category.model import Category

logger = logging.getLogger(__name__)


class CategoryRepository(BaseRepository[Category]):
    """Repository for reading hierarchical categories (read-only by design).

    Usage::

        repo = CategoryRepository(model=Category)
        async with repo:
            root_cats, total = await repo.list_all(limit=50, offset=0)
            children = await repo.get_children(parent_id=1)
    """

    TABLE = "category"

    async def get_by_id(self, category_id: int) -> Category | None:
        return await self.find_by_id(self.TABLE, category_id)

    async def list_all(
        self, *, limit: int | None = None, offset: int | None = None
    ) -> tuple[list[Category], int]:
        total = await self.count(self.TABLE)
        rows = await self.all(
            self.TABLE, limit=limit, offset=offset, order_by=["title"],
        )
        return rows, total

    async def get_children(self, parent_id: int) -> list[Category]:
        return await self.find(self.TABLE, {"parent_id": parent_id}, order_by=["title"])
