from typing import Any, List from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.core.auth import get_current_active_user from app.crud import category as category_crud from app.db.session import get_db from app.models import User from app.schemas.category import Category, CategoryCreate, CategoryUpdate router = APIRouter() @router.get("/", response_model=List[Category]) def read_categories( db: Session = Depends(get_db), skip: int = 0, limit: int = 100, current_user: User = Depends(get_current_active_user), ) -> Any: categories = category_crud.get_multi(db, skip=skip, limit=limit) return categories @router.post("/", response_model=Category) def create_category( *, db: Session = Depends(get_db), category_in: CategoryCreate, current_user: User = Depends(get_current_active_user), ) -> Any: category = category_crud.get_by_name(db, name=category_in.name) if category: raise HTTPException( status_code=400, detail="Category with this name already exists.", ) category = category_crud.create(db, obj_in=category_in) return category @router.put("/{id}", response_model=Category) def update_category( *, db: Session = Depends(get_db), id: int, category_in: CategoryUpdate, current_user: User = Depends(get_current_active_user), ) -> Any: category = category_crud.get(db, id=id) if not category: raise HTTPException(status_code=404, detail="Category not found") category = category_crud.update(db, db_obj=category, obj_in=category_in) return category @router.get("/{id}", response_model=Category) def read_category( *, db: Session = Depends(get_db), id: int, current_user: User = Depends(get_current_active_user), ) -> Any: category = category_crud.get(db, id=id) if not category: raise HTTPException(status_code=404, detail="Category not found") return category @router.delete("/{id}", response_model=Category) def delete_category( *, db: Session = Depends(get_db), id: int, current_user: User = Depends(get_current_active_user), ) -> Any: category = category_crud.get(db, id=id) if not category: raise HTTPException(status_code=404, detail="Category not found") category = category_crud.remove(db, id=id) return category