from accounts.supabase_client import get_client

# Cart is persisted per-customer in Supabase (pickker_cart_items), not in the
# Django session — so it survives logout, session expiry, or the customer
# closing the browser mid-shopping. It's only cleared once an order is
# actually placed from it (see market/views.py checkout_schedule).
#
# A cart row's identity is (customer_id, product_id, measure_id) — measure_id
# is nullable (NULL = the product's plain legacy unit/price), so a customer
# can hold e.g. both "2 kg" and "1 bucket" of the same product as separate
# lines at once.


def get_cart(customer_id):
    """Returns the raw list of cart rows: [{id, product_id, quantity, measure_id}, ...]."""
    resp = (
        get_client()
        .table('pickker_cart_items')
        .select('id, product_id, quantity, measure_id')
        .eq('customer_id', customer_id)
        .execute()
    )
    return resp.data


def _find_row(client, customer_id, product_id, measure_id):
    query = client.table('pickker_cart_items').select('id, quantity').eq('customer_id', customer_id).eq('product_id', product_id)
    query = query.is_('measure_id', 'null') if measure_id is None else query.eq('measure_id', measure_id)
    resp = query.execute()
    return resp.data[0] if resp.data else None


def add_to_cart(customer_id, product_id, qty=1, measure_id=None):
    client = get_client()
    row = _find_row(client, customer_id, product_id, measure_id)
    if row:
        client.table('pickker_cart_items').update({'quantity': row['quantity'] + qty}).eq('id', row['id']).execute()
    else:
        client.table('pickker_cart_items').insert({
            'customer_id': customer_id, 'product_id': product_id, 'quantity': qty, 'measure_id': measure_id,
        }).execute()


def set_cart_item_qty(cart_item_id, qty):
    if qty <= 0:
        remove_cart_item(cart_item_id)
        return
    get_client().table('pickker_cart_items').update({'quantity': qty}).eq('id', cart_item_id).execute()


def remove_cart_item(cart_item_id):
    get_client().table('pickker_cart_items').delete().eq('id', cart_item_id).execute()


def clear_cart(customer_id):
    get_client().table('pickker_cart_items').delete().eq('customer_id', customer_id).execute()
