"""Admin-managed catalog of delivery vehicles — both B2B trucks (Tricycle,
Small Truck, Large Truck, ...) and B2C vehicles (Motorcycle, Car, Bicycle),
unified into one table since both need the exact same things: an open list
admin can add to (not a fixed enum), an icon, a max weight capacity that
filters who's even offered for a given order's weight, and a delivery rate.
`segment` ('b2c' or 'b2b') is the only thing that distinguishes them —
which picker-facing dropdown offers a row, and which fee model reads it."""

from django.core.cache import cache

from accounts.supabase_client import get_client

# Truck types barely ever change but are read on every checkout step —
# cached with a short TTL, invalidated immediately on any admin edit.
_ACTIVE_CACHE_KEY = 'pickker_truck_types_active'
_ALL_CACHE_KEY = 'pickker_truck_types_all'
_CACHE_TTL = 60


def _invalidate():
    cache.delete(_ACTIVE_CACHE_KEY)
    for segment in ('b2c', 'b2b'):
        cache.delete(f'{_ACTIVE_CACHE_KEY}:{segment}')
    cache.delete(_ALL_CACHE_KEY)


def get_active_truck_types(segment=None):
    """segment=None returns every active type (both b2c and b2b) — used by
    the admin-facing listing/pricing contexts where segment doesn't matter.
    Picker-facing dropdowns and matching logic should always pass the
    segment they actually want."""
    cache_key = _ACTIVE_CACHE_KEY if segment is None else f'{_ACTIVE_CACHE_KEY}:{segment}'
    truck_types = cache.get(cache_key)
    if truck_types is None:
        query = get_client().table('pickker_truck_types').select('*').eq('is_active', True)
        if segment is not None:
            query = query.eq('segment', segment)
        truck_types = query.order('base_rate').execute().data
        cache.set(cache_key, truck_types, _CACHE_TTL)
    return truck_types


def get_all_truck_types():
    truck_types = cache.get(_ALL_CACHE_KEY)
    if truck_types is None:
        resp = get_client().table('pickker_truck_types').select('*').order('base_rate').execute()
        truck_types = resp.data
        cache.set(_ALL_CACHE_KEY, truck_types, _CACHE_TTL)
    return truck_types


def get_truck_type(truck_type_id):
    if not truck_type_id:
        return None
    resp = get_client().table('pickker_truck_types').select('*').eq('id', truck_type_id).execute()
    return resp.data[0] if resp.data else None


def create_truck_type(name, capacity_label, max_weight_kg, base_rate, icon='', icon_url=None, segment='b2b', per_km_rate=None):
    row = {
        'name': name.strip(),
        'capacity_label': capacity_label.strip(),
        'max_weight_kg': max_weight_kg,
        'base_rate': base_rate,
        'icon': icon.strip(),
        'segment': segment,
        'per_km_rate': per_km_rate,
    }
    if icon_url is not None:
        row['icon_url'] = icon_url
    get_client().table('pickker_truck_types').insert(row).execute()
    _invalidate()


def update_truck_type(truck_type_id, name, capacity_label, max_weight_kg, base_rate, icon='', icon_url=None, segment='b2b', per_km_rate=None):
    row = {
        'name': name.strip(),
        'capacity_label': capacity_label.strip(),
        'max_weight_kg': max_weight_kg,
        'base_rate': base_rate,
        'icon': icon.strip(),
        'segment': segment,
        'per_km_rate': per_km_rate,
    }
    if icon_url is not None:
        row['icon_url'] = icon_url
    get_client().table('pickker_truck_types').update(row).eq('id', truck_type_id).execute()
    _invalidate()


def get_picker_vehicle_display(picker_user_id):
    """What to draw for this picker's marker on any map — their B2C vehicle
    (motorcycle/car/bicycle) or, for a B2B picker, their truck type's own
    admin-set icon. Used everywhere a picker's live/static position is shown
    (checkout picker selection, customer order tracking, admin order
    tracking, the picker's own live-navigation view) so the marker always
    matches what they're actually driving."""
    resp = get_client().table('pickker_picker_profiles').select('vehicle_type, truck_type_id').eq('user_id', picker_user_id).execute()
    if not resp.data:
        return {'vehicle_type': 'car', 'truck_icon': None, 'truck_icon_url': None}
    profile = resp.data[0]
    truck_icon = None
    truck_icon_url = None
    if profile.get('truck_type_id'):
        truck = get_truck_type(profile['truck_type_id'])
        truck_icon = truck['icon'] if truck else None
        truck_icon_url = truck.get('icon_url') if truck else None
    return {'vehicle_type': profile.get('vehicle_type') or 'car', 'truck_icon': truck_icon, 'truck_icon_url': truck_icon_url}


def get_per_km_rate_for_picker(picker_user_id):
    """The per-km delivery rate for whatever vehicle this picker (B2C or
    B2B) has registered — None if they have no truck_type_id set, or their
    vehicle type has no rate of its own (calculate_delivery_fee then falls
    back to the platform flat rate, same as always)."""
    if not picker_user_id:
        return None
    resp = get_client().table('pickker_picker_profiles').select('truck_type_id').eq('user_id', picker_user_id).execute()
    if not resp.data or not resp.data[0].get('truck_type_id'):
        return None
    truck = get_truck_type(resp.data[0]['truck_type_id'])
    return truck.get('per_km_rate') if truck else None


def toggle_truck_type_active(truck_type_id):
    client = get_client()
    resp = client.table('pickker_truck_types').select('is_active').eq('id', truck_type_id).execute()
    if resp.data:
        current = resp.data[0]['is_active']
        client.table('pickker_truck_types').update({'is_active': not current}).eq('id', truck_type_id).execute()
        _invalidate()
        return not current
    return None
