from typing import List from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from app.db.session import get_db from app.crud import category as category_crud from app.schemas.category import Category, CategoryCreate, CategoryUpdate router = APIRouter() @router.get("/", response_model=List[Category]) def read_categories(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): """ Retrieve categories. """ categories = category_crud.get_categories(db, skip=skip, limit=limit) return categories @router.post("/", response_model=Category, status_code=status.HTTP_201_CREATED) def create_category(category: CategoryCreate, db: Session = Depends(get_db)): """ Create new category. """ # Check if category with same name already exists existing_category = category_crud.get_category_by_name(db, name=category.name) if existing_category: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Category with this name already exists", ) return category_crud.create_category(db=db, category=category) @router.get("/{category_id}", response_model=Category) def read_category(category_id: int, db: Session = Depends(get_db)): """ Get category by ID. """ db_category = category_crud.get_category(db, category_id=category_id) if db_category is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Category not found" ) return db_category @router.put("/{category_id}", response_model=Category) def update_category( category_id: int, category: CategoryUpdate, db: Session = Depends(get_db) ): """ Update category. """ # Check if category exists db_category = category_crud.get_category(db, category_id=category_id) if db_category is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Category not found" ) # Check if name is being updated and already exists if category.name and category.name != db_category.name: existing_category = category_crud.get_category_by_name(db, name=category.name) if existing_category: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Category with this name already exists", ) return category_crud.update_category( db=db, category_id=category_id, category=category ) @router.delete("/{category_id}", status_code=status.HTTP_204_NO_CONTENT) def delete_category(category_id: int, db: Session = Depends(get_db)): """ Delete category. """ success = category_crud.delete_category(db=db, category_id=category_id) if not success: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Category not found" )