from collections.abc import AsyncGenerator
from typing import Annotated

from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from src.db.database import get_db
from src.schemas import CategoryListResponse, CategoryResponse
from src.services import CategoryService

router = APIRouter()


async def get_category_service(
    db: Annotated[AsyncSession, Depends(get_db)],
) -> AsyncGenerator[CategoryService, None]:
    """Dependency for CategoryService."""
    yield CategoryService(db)


@router.get("", response_model=CategoryListResponse)
async def list_categories(
    service: Annotated[CategoryService, Depends(get_category_service)],
) -> CategoryListResponse:
    """List all categories with question counts."""
    categories_with_counts = await service.get_categories()

    items = [
        CategoryResponse(
            id=category.id,
            name=category.name,
            slug=category.slug,
            description=category.description,
            question_count=count,
        )
        for category, count in categories_with_counts
    ]

    return CategoryListResponse(items=items)
