from typing import Any, List from fastapi import APIRouter, Depends, HTTPException, Path, Query from sqlalchemy.orm import Session from app.db.deps import get_current_active_user, get_db from app.models.gift import Gift from app.models.user import User from app.schemas.gift import Gift as GiftSchema from app.schemas.gift import GiftCreate, GiftUpdate router = APIRouter() @router.get("", response_model=List[GiftSchema]) def read_gifts( db: Session = Depends(get_db), skip: int = 0, limit: int = 100, recipient_name: str = Query(None, description="Filter by recipient name"), occasion: str = Query(None, description="Filter by occasion"), purchased: bool = Query(None, description="Filter by purchased status"), current_user: User = Depends(get_current_active_user), ) -> Any: """ Retrieve gifts. """ query = db.query(Gift).filter(Gift.user_id == current_user.id) # Apply filters if provided if recipient_name: query = query.filter(Gift.recipient_name == recipient_name) if occasion: query = query.filter(Gift.occasion == occasion) if purchased is not None: query = query.filter(Gift.purchased == purchased) # Apply pagination gifts = query.offset(skip).limit(limit).all() return gifts @router.post("", response_model=GiftSchema) def create_gift( *, db: Session = Depends(get_db), gift_in: GiftCreate, current_user: User = Depends(get_current_active_user), ) -> Any: """ Create new gift. """ gift = Gift( **gift_in.dict(), user_id=current_user.id ) db.add(gift) db.commit() db.refresh(gift) return gift @router.put("/{id}", response_model=GiftSchema) def update_gift( *, db: Session = Depends(get_db), id: int = Path(..., description="The ID of the gift to update"), gift_in: GiftUpdate, current_user: User = Depends(get_current_active_user), ) -> Any: """ Update a gift. """ gift = db.query(Gift).filter(Gift.id == id, Gift.user_id == current_user.id).first() if not gift: raise HTTPException(status_code=404, detail="Gift not found") update_data = gift_in.dict(exclude_unset=True) for field, value in update_data.items(): setattr(gift, field, value) db.add(gift) db.commit() db.refresh(gift) return gift @router.get("/{id}", response_model=GiftSchema) def read_gift( *, db: Session = Depends(get_db), id: int = Path(..., description="The ID of the gift to get"), current_user: User = Depends(get_current_active_user), ) -> Any: """ Get gift by ID. """ gift = db.query(Gift).filter(Gift.id == id, Gift.user_id == current_user.id).first() if not gift: raise HTTPException(status_code=404, detail="Gift not found") return gift @router.delete("/{id}", status_code=204, response_model=None) def delete_gift( *, db: Session = Depends(get_db), id: int = Path(..., description="The ID of the gift to delete"), current_user: User = Depends(get_current_active_user), ) -> Any: """ Delete a gift. """ gift = db.query(Gift).filter(Gift.id == id, Gift.user_id == current_user.id).first() if not gift: raise HTTPException(status_code=404, detail="Gift not found") db.delete(gift) db.commit() return None