from typing import List, Optional
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models.category import Category


class CategoryRepository:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def list_all(self) -> List[Category]:
        """List all category records ordered alphabetically by name"""
        query = select(Category).order_by(Category.name.asc())
        result = await self.db.execute(query)
        return list(result.scalars().all())

    async def create(self, name: str) -> Category:
        """Create a new category record"""
        category = Category(name=name)
        self.db.add(category)
        await self.db.flush()
        return category

    async def get_by_name(self, name: str) -> Optional[Category]:
        """Fetch a category record by name (case-insensitive)"""
        query = select(Category).where(Category.name.ilike(name))
        result = await self.db.execute(query)
        return result.scalar_one_or_none()
