class PickerSession:
    """Lightweight stand-in for request.user, backed by request.session
    (since real user records live in Supabase, not Django's ORM)."""

    def __init__(self, data):
        self._data = data or {}

    @property
    def is_authenticated(self):
        return bool(self._data)

    @property
    def id(self):
        return self._data.get('id')

    @property
    def email(self):
        return self._data.get('email')

    @property
    def role(self):
        return self._data.get('role')

    @property
    def first_name(self):
        return self._data.get('first_name', '')

    @property
    def account_type(self):
        return self._data.get('account_type')

    @property
    def is_b2b(self):
        return self._data.get('account_type') == 'b2b'

    @property
    def is_registered_business(self):
        """True once someone is not just toggled to B2B (toggle_business_mode
        is a one-click, zero-detail switch anyone can flip) but has actually
        supplied a business name — either at signup (required there for a
        B2B account, see SignupForm.clean()) or afterward via profile_edit.
        Gates business-only nav (e.g. "My Fleet") so a customer who flipped
        the switch out of curiosity doesn't land on fleet-registration UI
        meant for an actual registered business."""
        return self._data.get('account_type') == 'b2b' and bool(self._data.get('business_name'))


def picker_session(request):
    """Runs on every single page render (nav cart/notification badges), so
    it's worth keeping the Supabase round trips to a minimum: independent
    lookups run in parallel (safe now that accounts.supabase_client forces
    HTTP/1.1 — see the comment there), and the customer's orders are fetched
    exactly once (previously queried twice — once for status changes, once
    for message-count order ids — doubling the request's network cost)."""
    from concurrent.futures import ThreadPoolExecutor

    picker_user = request.session.get('picker_user')
    cart_count = 0
    order_notification_count = 0
    if picker_user and picker_user.get('role') == 'customer':
        from market.cart import get_cart
        from market.messaging import get_unseen_message_count
        from market.order_notifications import count_unseen_status_changes, get_seen_map
        from market.supabase_orders import get_orders_with_status_for_customer

        customer_id = picker_user['id']
        # If the view already fetched+updated the seen-map this same request
        # (e.g. order_list/order_detail marking orders as seen), reuse that
        # instead of a redundant read of the same row.
        cached_seen_map = getattr(request, '_seen_map_cache', None)
        with ThreadPoolExecutor(max_workers=3 if cached_seen_map is None else 2) as executor:
            cart_future = executor.submit(get_cart, customer_id)
            orders_future = executor.submit(get_orders_with_status_for_customer, customer_id)
            seen_map_future = None if cached_seen_map is not None else executor.submit(get_seen_map, customer_id)
            cart = cart_future.result()
            orders = orders_future.result()
            seen_map = cached_seen_map if cached_seen_map is not None else seen_map_future.result()

        cart_count = sum(row['quantity'] for row in cart)
        order_ids = [o['id'] for o in orders]
        order_notification_count = count_unseen_status_changes(orders, seen_map)
        order_notification_count += get_unseen_message_count(customer_id, order_ids)
    elif picker_user and picker_user.get('role') == 'picker':
        from market.messaging import get_unseen_message_count
        from market.supabase_orders import get_order_ids_for_picker

        order_notification_count = get_unseen_message_count(picker_user['id'], get_order_ids_for_picker(picker_user['id']))

    from django.conf import settings

    return {
        'picker_session': PickerSession(picker_user),
        'cart_count': cart_count,
        'order_notification_count': order_notification_count,
        'vapid_public_key': settings.VAPID_PUBLIC_KEY,
    }
