from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession

from src.models import Category, QuestionCategory


class CategoryService:
    def __init__(self, db: AsyncSession) -> None:
        self.db = db

    async def get_categories(self) -> list[tuple[Category, int]]:
        query = (
            select(Category, func.count(QuestionCategory.question_id).label("question_count"))
            .outerjoin(QuestionCategory, Category.id == QuestionCategory.category_id)
            .group_by(Category.id)
            .order_by(Category.name)
        )
        result = await self.db.execute(query)
        return [(row[0], row[1]) for row in result.all()]

    async def get_category_by_slug(self, slug: str) -> Category | None:
        query = select(Category).where(Category.slug == slug)
        result = await self.db.execute(query)
        return result.scalar_one_or_none()
