"""Tracks which order-status changes a customer has already seen, so the nav
can flash a notification count when a picker or admin advances an order
(e.g. confirmed -> picking) and the customer hasn't looked at it yet.

Seen state is stored as {order_id: last_seen_status} on the customer's own
profile row (order_status_seen jsonb), not in the session, so it survives
logout/login same as cart and chat history do elsewhere in this app.
"""

from accounts.supabase_client import get_client

# Genuinely still-in-progress statuses — excludes 'delivered' and 'cancelled',
# which are done and shouldn't be flashed as "in progress" on login.
_IN_PROGRESS_STATUSES = ['pending_payment', 'confirmed', 'picking', 'in_transit']


def get_seen_map(customer_id):
    resp = get_client().table('pickker_customer_profiles').select('order_status_seen').eq('user_id', customer_id).execute()
    if resp.data and resp.data[0].get('order_status_seen'):
        return resp.data[0]['order_status_seen']
    return {}


def _save_seen_map(customer_id, seen_map):
    get_client().table('pickker_customer_profiles').update({'order_status_seen': seen_map}).eq('user_id', customer_id).execute()


def mark_order_seen(customer_id, order_id, status, request=None):
    """Call right after the customer views an order (or places it) so its
    current status no longer counts as an unseen change. Pass the current
    `request` and the freshly-updated seen_map is cached on it, so the
    `picker_session` context processor's own seen-map lookup later in this
    same request/response cycle can reuse it instead of re-querying."""
    seen_map = get_seen_map(customer_id)
    seen_map[str(order_id)] = status
    _save_seen_map(customer_id, seen_map)
    if request is not None:
        request._seen_map_cache = seen_map
    return seen_map


def mark_all_orders_seen(customer_id, orders, request=None):
    seen_map = get_seen_map(customer_id)
    for order in orders:
        seen_map[str(order['id'])] = order['status']
    _save_seen_map(customer_id, seen_map)
    if request is not None:
        request._seen_map_cache = seen_map
    return seen_map


def count_unseen_status_changes(orders, seen_map):
    """Pure version of get_unseen_status_changes for callers that already
    have both the order list and seen-map in hand (e.g. the nav badge, which
    fetches these once itself and reuses them instead of re-querying)."""
    return sum(1 for o in orders if seen_map.get(str(o['id'])) != o['status'])


def get_active_orders_for_login_flash(customer_id):
    """Orders still in progress (not delivered/cancelled) to summarize in a
    flash message right after login, so the customer immediately knows
    where things stand."""
    resp = (
        get_client()
        .table('pickker_orders')
        .select('id, status')
        .eq('customer_id', customer_id)
        .in_('status', _IN_PROGRESS_STATUSES)
        .order('created_at', desc=True)
        .execute()
    )
    return resp.data
