from typing import Any, List from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from app.api.deps import get_current_admin_user, get_current_active_user, get_db from app.crud.product import product, category from app.models.user import User from app.schemas.product import ( Product, ProductCreate, ProductUpdate, Category, CategoryCreate, CategoryUpdate, ) router = APIRouter() # Product routes @router.get("/", response_model=List[Product]) def read_products( db: Session = Depends(get_db), skip: int = 0, limit: int = 100, ) -> Any: """ Retrieve products. """ return product.get_active(db, skip=skip, limit=limit) @router.post("/", response_model=Product) def create_product( *, db: Session = Depends(get_db), product_in: ProductCreate, current_user: User = Depends(get_current_admin_user), ) -> Any: """ Create new product. Only for admins. """ return product.create(db, obj_in=product_in) @router.get("/{product_id}", response_model=Product) def read_product( *, db: Session = Depends(get_db), product_id: int, ) -> Any: """ Get product by ID. """ db_product = product.get(db, id=product_id) if not db_product: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Product not found", ) return db_product @router.put("/{product_id}", response_model=Product) def update_product( *, db: Session = Depends(get_db), product_id: int, product_in: ProductUpdate, current_user: User = Depends(get_current_admin_user), ) -> Any: """ Update a product. Only for admins. """ db_product = product.get(db, id=product_id) if not db_product: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Product not found", ) return product.update(db, db_obj=db_product, obj_in=product_in) @router.delete("/{product_id}", response_model=Product) def delete_product( *, db: Session = Depends(get_db), product_id: int, current_user: User = Depends(get_current_admin_user), ) -> Any: """ Delete a product. Only for admins. """ db_product = product.get(db, id=product_id) if not db_product: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Product not found", ) return product.remove(db, id=product_id) @router.get("/category/{category_id}", response_model=List[Product]) def read_products_by_category( *, db: Session = Depends(get_db), category_id: int, skip: int = 0, limit: int = 100, ) -> Any: """ Get products by category. """ db_category = category.get(db, id=category_id) if not db_category: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Category not found", ) return product.get_by_category(db, category_id=category_id, skip=skip, limit=limit)