from sqlalchemy.orm import Session
from app.models import Cart, CartItem, Product
from app.schemas.cart import CartItemCreate, CartItemUpdate
from typing import Optional
import uuid


def get_or_create_cart(db: Session, user_id: int) -> Cart:
    cart = db.query(Cart).filter(Cart.user_id == user_id).first()
    if not cart:
        cart = Cart(user_id=user_id)
        db.add(cart)
        db.commit()
        db.refresh(cart)
    return cart


def add_to_cart(db: Session, user_id: int, item: CartItemCreate) -> CartItem:
    cart = get_or_create_cart(db, user_id)

    # Check if item already exists
    existing_item = (
        db.query(CartItem)
        .filter(
            CartItem.cart_id == cart.id,
            CartItem.product_id == item.product_id,
            CartItem.size == item.size,
            CartItem.color == item.color,
        )
        .first()
    )

    if existing_item:
        existing_item.quantity += item.quantity
        db.commit()
        db.refresh(existing_item)
        return existing_item

    item_data = item.model_dump() if hasattr(item, 'model_dump') else item.dict()
    cart_item = CartItem(cart_id=cart.id, **item_data)
    db.add(cart_item)
    db.commit()
    db.refresh(cart_item)
    return cart_item


def get_cart(db: Session, user_id: int) -> Optional[Cart]:
    return db.query(Cart).filter(Cart.user_id == user_id).first()


def update_cart_item(
    db: Session, cart_item_id: int, update: CartItemUpdate
) -> Optional[CartItem]:
    cart_item = db.query(CartItem).filter(CartItem.id == cart_item_id).first()
    if not cart_item:
        return None

    if update.quantity:
        cart_item.quantity = update.quantity

    db.commit()
    db.refresh(cart_item)
    return cart_item


def remove_from_cart(db: Session, cart_item_id: int) -> bool:
    cart_item = db.query(CartItem).filter(CartItem.id == cart_item_id).first()
    if not cart_item:
        return False

    db.delete(cart_item)
    db.commit()
    return True


def clear_cart(db: Session, user_id: int) -> bool:
    cart = get_cart(db, user_id)
    if not cart:
        return False

    db.query(CartItem).filter(CartItem.cart_id == cart.id).delete()
    db.commit()
    return True
