from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api import deps
from app.schemas.shopping_cart import CartItemCreate, CartItemResponse, ShoppingCartResponse
from app.services import shopping_cart_service
from app.models.shopping_cart import ShoppingCart

router = APIRouter()

@router.post("/add", response_model=CartItemResponse)
def add_item_to_cart(
    req: CartItemCreate,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Adds a product to the shopping cart of the logged-in user.
    If the cart does not exist, a new one is created, and if the product already exists, its quantity is updated.
    """
    cart_item = shopping_cart_service.add_item_to_cart(db, current_user.id, req.product_id, req.quantity)
    return cart_item

@router.get("/", response_model=ShoppingCartResponse)
def get_cart(
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Retrieves the shopping cart of the logged-in user.
    If the cart does not exist, an empty cart is created and returned.
    """
    cart = shopping_cart_service.get_user_cart(db, current_user.id)
    if not cart:
        cart = ShoppingCart(user_id=current_user.id)
        db.add(cart)
        db.commit()
        db.refresh(cart)
    return cart

@router.delete("/remove", response_model=CartItemResponse)
def remove_item_from_cart(
    req: CartItemCreate,
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    Removes a specific product from the shopping cart of the logged-in user.
    """
    removed_item = shopping_cart_service.remove_item_from_cart(db, current_user.id, req.product_id)
    return removed_item

@router.delete("/clear", status_code=status.HTTP_204_NO_CONTENT)
def clear_cart(
    db: Session = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user)
):
    """
    쇼핑카트의 모든 아이템을 제거합니다.
    
    이 엔드포인트는:
    1. 사용자의 쇼핑카트를 찾습니다.
    2. 카트에 있는 모든 상품을 제거합니다.
    3. 성공 시 204 No Content를 반환합니다.
    """
    shopping_cart_service.clear_cart(db, current_user.id)
    return None