71 lines
2.1 KiB
Python
71 lines
2.1 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
from typing import List
|
|
from app.database.database import get_db
|
|
from app.models import Wishlist, Product
|
|
from app.schemas.product import ProductResponse
|
|
from app.services.auth import verify_token
|
|
|
|
router = APIRouter(prefix="/api/wishlist", tags=["wishlist"])
|
|
|
|
|
|
def get_user_id_from_token(token: str) -> int:
|
|
user_id = verify_token(token)
|
|
if user_id is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid token",
|
|
)
|
|
return user_id
|
|
|
|
|
|
@router.get("", response_model=List[ProductResponse])
|
|
def get_wishlist(token: str, db: Session = Depends(get_db)):
|
|
user_id = get_user_id_from_token(token)
|
|
wishlist_items = (
|
|
db.query(Wishlist).filter(Wishlist.user_id == user_id).all()
|
|
)
|
|
products = [
|
|
db.query(Product).filter(Product.id == item.product_id).first()
|
|
for item in wishlist_items
|
|
]
|
|
return products
|
|
|
|
|
|
@router.post("/{product_id}")
|
|
def add_to_wishlist(product_id: int, token: str, db: Session = Depends(get_db)):
|
|
user_id = get_user_id_from_token(token)
|
|
|
|
existing = (
|
|
db.query(Wishlist)
|
|
.filter(Wishlist.user_id == user_id, Wishlist.product_id == product_id)
|
|
.first()
|
|
)
|
|
if existing:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Product already in wishlist",
|
|
)
|
|
|
|
wishlist_item = Wishlist(user_id=user_id, product_id=product_id)
|
|
db.add(wishlist_item)
|
|
db.commit()
|
|
return {"message": "Product added to wishlist"}
|
|
|
|
|
|
@router.delete("/{product_id}")
|
|
def remove_from_wishlist(product_id: int, token: str, db: Session = Depends(get_db)):
|
|
user_id = get_user_id_from_token(token)
|
|
|
|
wishlist_item = (
|
|
db.query(Wishlist)
|
|
.filter(Wishlist.user_id == user_id, Wishlist.product_id == product_id)
|
|
.first()
|
|
)
|
|
if not wishlist_item:
|
|
raise HTTPException(status_code=404, detail="Item not in wishlist")
|
|
|
|
db.delete(wishlist_item)
|
|
db.commit()
|
|
return {"message": "Product removed from wishlist"}
|