from typing import Any, List, Optional from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy.orm import Session from app import models, schemas from app.api import deps router = APIRouter() @router.get("/", response_model=List[schemas.Product]) def read_products( db: Session = Depends(deps.get_db), skip: int = 0, limit: int = 100, name: Optional[str] = None, min_price: Optional[float] = None, max_price: Optional[float] = None, ) -> Any: """ Retrieve products with optional filtering. """ query = db.query(models.Product).filter(models.Product.is_active == True) if name: query = query.filter(models.Product.name.ilike(f"%{name}%")) if min_price is not None: query = query.filter(models.Product.price >= min_price) if max_price is not None: query = query.filter(models.Product.price <= max_price) products = query.offset(skip).limit(limit).all() return products @router.post("/", response_model=schemas.Product) def create_product( *, db: Session = Depends(deps.get_db), product_in: schemas.ProductCreate, current_user: models.User = Depends(deps.get_current_active_admin), ) -> Any: """ Create new product. """ product = models.Product( name=product_in.name, description=product_in.description, price=product_in.price, stock=product_in.stock, image_url=product_in.image_url, is_active=product_in.is_active, ) db.add(product) db.commit() db.refresh(product) return product @router.get("/{product_id}", response_model=schemas.Product) def read_product( *, db: Session = Depends(deps.get_db), product_id: int, ) -> Any: """ Get product by ID. """ product = db.query(models.Product).filter( models.Product.id == product_id, models.Product.is_active == True ).first() if not product: raise HTTPException( status_code=404, detail="Product not found" ) return product @router.put("/{product_id}", response_model=schemas.Product) def update_product( *, db: Session = Depends(deps.get_db), product_id: int, product_in: schemas.ProductUpdate, current_user: models.User = Depends(deps.get_current_active_admin), ) -> Any: """ Update a product. """ product = db.query(models.Product).filter(models.Product.id == product_id).first() if not product: raise HTTPException( status_code=404, detail="Product not found", ) update_data = product_in.dict(exclude_unset=True) for field, value in update_data.items(): setattr(product, field, value) db.add(product) db.commit() db.refresh(product) return product @router.delete("/{product_id}", response_model=schemas.Product) def delete_product( *, db: Session = Depends(deps.get_db), product_id: int, current_user: models.User = Depends(deps.get_current_active_admin), ) -> Any: """ Delete a product. """ product = db.query(models.Product).filter(models.Product.id == product_id).first() if not product: raise HTTPException( status_code=404, detail="Product not found", ) # Soft delete by marking as inactive product.is_active = False db.add(product) db.commit() db.refresh(product) return product