"""Live picker-to-destination navigation for an in-progress delivery.

When a picker marks their order in_transit (accounts.views.advance_order),
their live navigation page begins recording GPS position (picker_live_lat/
lng on the order — scoped to that one order/delivery, not a standalone
always-on tracker) as their browser reports it. The page then re-fetches a
fresh driving route from wherever the picker currently is to the customer's
destination, so the suggested route updates as they move rather than
staying fixed to their position when the order was first placed.
"""

from datetime import datetime, timezone

from accounts.supabase_client import get_client


def update_picker_location(order_id, picker_id, lat, lng):
    """Called repeatedly (every few seconds) while the picker's live
    navigation page is open. Scoped to picker_id so a picker can only ever
    update the position on their own order."""
    client = get_client()
    resp = (
        client.table('pickker_orders')
        .update({
            'picker_live_lat': lat,
            'picker_live_lng': lng,
            'picker_live_updated_at': datetime.now(timezone.utc).isoformat(),
        })
        .eq('id', order_id)
        .eq('picker_id', picker_id)
        .execute()
    )
    return bool(resp.data)


def get_live_location(order_id):
    resp = (
        get_client()
        .table('pickker_orders')
        .select('picker_live_lat, picker_live_lng, picker_live_updated_at')
        .eq('id', order_id)
        .execute()
    )
    if not resp.data:
        return None
    row = resp.data[0]
    if row['picker_live_lat'] is None:
        return None
    return {
        'lat': float(row['picker_live_lat']),
        'lng': float(row['picker_live_lng']),
        'updated_at': row['picker_live_updated_at'],
    }
