from typing import List
from sqlalchemy.ext.asyncio import AsyncSession
from app.repositories.category_repository import CategoryRepository
from app.db.models.category import Category
from app.core.exceptions import CategoryAlreadyExistsException


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

    async def list_categories(self) -> List[Category]:
        """Returns all categories alphabetical list"""
        return await self.repo.list_all()

    async def create_category(self, name: str) -> Category:
        """Creates a new category, validating uniqueness first"""
        name_clean = name.strip()
        existing = await self.repo.get_by_name(name_clean)
        if existing:
            raise CategoryAlreadyExistsException(name_clean)

        category = await self.repo.create(name_clean)
        await self.db.commit()
        return category
