from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from app.core.dependencies import get_category_service
from app.core.exceptions import CategoryAlreadyExistsException
from app.schemas.category import CategoryCreate, CategoryResponse
from app.services.category_service import CategoryService

router = APIRouter(prefix="/categories", tags=["categories"])


@router.get("", response_model=List[CategoryResponse])
async def list_categories(
    service: CategoryService = Depends(get_category_service),
):
    """
    Returns the list of all available categories ordered alphabetically.
    """
    return await service.list_categories()


@router.post("", response_model=CategoryResponse, status_code=status.HTTP_201_CREATED)
async def create_category(
    category_in: CategoryCreate,
    service: CategoryService = Depends(get_category_service),
):
    """
    Creates a new custom category. The name must be unique.
    """
    try:
        return await service.create_category(name=category_in.name)
    except CategoryAlreadyExistsException as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e),
        )
