from .models import CartItem, Product, Color, Size

def get_or_create_cart_id(request):
    """Get the cart ID from the session or create a new one"""
    if 'cart_id' not in request.session:
        request.session['cart_id'] = request.session.session_key or request.session.create()
    return request.session['cart_id']

def get_cart_items(request):
    """Get all cart items for the current session"""
    cart_id = get_or_create_cart_id(request)
    return CartItem.objects.filter(session_id=cart_id)

def add_to_cart(request, product_id, quantity=1, color_id=None, size_id=None):
    """Add a product to the cart or update its quantity"""
    product = Product.objects.get(id=product_id)
    cart_id = get_or_create_cart_id(request)

    color = Color.objects.get(id=color_id) if color_id else None
    size = Size.objects.get(id=size_id) if size_id else None

    try:
        # Try to get existing cart item with the same product, color, and size
        cart_item = CartItem.objects.get(
            product=product,
            session_id=cart_id,
            color=color,
            size=size
        )
        cart_item.quantity += quantity
        cart_item.save()
    except CartItem.DoesNotExist:
        # Create new cart item
        cart_item = CartItem.objects.create(
            product=product,
            quantity=quantity,
            session_id=cart_id,
            color=color,
            size=size
        )

    return cart_item

def remove_from_cart(request, product_id):
    """Remove a product from the cart"""
    cart_id = get_or_create_cart_id(request)
    CartItem.objects.filter(product_id=product_id, session_id=cart_id).delete()

def update_cart_item(request, product_id, quantity):
    """Update the quantity of a cart item"""
    cart_id = get_or_create_cart_id(request)
    cart_item = CartItem.objects.get(product_id=product_id, session_id=cart_id)

    if quantity > 0:
        cart_item.quantity = quantity
        cart_item.save()
    else:
        cart_item.delete()

def get_cart_total(request):
    """Calculate the total price of all items in the cart"""
    return sum(item.product.price * item.quantity for item in get_cart_items(request))

def clear_cart(request):
    """Clear the cart"""
    cart_id = get_or_create_cart_id(request)
    CartItem.objects.filter(session_id=cart_id).delete()

# Add this function to your cart.py file
def get_cart_item(request, item_id):
    """Get a specific cart item by its ID"""
    cart_id = get_or_create_cart_id(request)
    try:
        return CartItem.objects.get(id=item_id, session_id=cart_id)
    except CartItem.DoesNotExist:
        raise Exception("Cart item not found")

def transfer_cart(request, old_session_key):
    """
    Transfer cart items from an anonymous session to an authenticated user's session
    """
    from django.contrib.sessions.models import Session
    from django.contrib.sessions.backends.db import SessionStore

    # Get the old session
    try:
        old_session = SessionStore(session_key=old_session_key)
        # Check if there are cart items in the old session
        if 'cart_items' in old_session:
            # Transfer cart items to the new session
            request.session['cart_items'] = old_session['cart_items']
            request.session.modified = True
    except Session.DoesNotExist:
        pass
