from sqlalchemy.orm import Session
from app.models.shopping_cart import ShoppingCart
from app.models.cart_item import CartItem
from fastapi import HTTPException

def add_item_to_cart(db: Session, user_id: int, product_id: int, quantity: int) -> CartItem:
    # Retrieve the user's shopping cart; create one if it doesn't exist
    cart = db.query(ShoppingCart).filter(ShoppingCart.user_id == user_id).first()
    if not cart:
        cart = ShoppingCart(user_id=user_id)
        db.add(cart)
        db.commit()
        db.refresh(cart)
    
    # Update quantity if the same product already exists; otherwise, add a new item
    cart_item = db.query(CartItem).filter(
        CartItem.cart_id == cart.id,
        CartItem.product_id == product_id
    ).first()

    if cart_item:
        cart_item.quantity += quantity
        db.commit()
        db.refresh(cart_item)
    else:
        cart_item = CartItem(cart_id=cart.id, product_id=product_id, quantity=quantity)
        db.add(cart_item)
        db.commit()
        db.refresh(cart_item)

    return cart_item

def get_user_cart(db: Session, user_id: int) -> ShoppingCart:
    return db.query(ShoppingCart).filter(ShoppingCart.user_id == user_id).first()

def remove_item_from_cart(db: Session, user_id: int, product_id: int) -> CartItem:
    # Check for the user's cart
    cart = db.query(ShoppingCart).filter(ShoppingCart.user_id == user_id).first()
    if not cart:
        raise HTTPException(status_code=404, detail="Shopping cart not found")
    
    # Check if the specific product exists
    cart_item = db.query(CartItem).filter(
        CartItem.cart_id == cart.id,
        CartItem.product_id == product_id
    ).first()
    if not cart_item:
        raise HTTPException(status_code=404, detail="Cart item not found")
    
    db.delete(cart_item)
    db.commit()
    return cart_item

def clear_cart(db: Session, user_id: int) -> bool:
    """
    사용자의 쇼핑 카트에서 모든 아이템을 제거합니다.
    
    Args:
        db: 데이터베이스 세션
        user_id: 사용자 ID
        
    Returns:
        bool: 성공 여부
        
    Raises:
        HTTPException: 쇼핑 카트가 없을 경우
    """
    # 사용자의 쇼핑 카트 확인
    cart = db.query(ShoppingCart).filter(ShoppingCart.user_id == user_id).first()
    if not cart:
        raise HTTPException(status_code=404, detail="Shopping cart not found")
    
    # 모든 카트 아이템 삭제
    db.query(CartItem).filter(CartItem.cart_id == cart.id).delete()
    db.commit()
    
    return True