"""Small shared lookups used by the nav badge to know which orders a user
is party to (for counting unseen messages) without duplicating this query
in every view that needs it."""

from accounts.supabase_client import get_client


def get_orders_with_status_for_customer(customer_id):
    """id+status (+schedule) for every order this customer has — the nav
    badge needs both the order ids (for the message-unread count) and the
    statuses (for the status-change count), so it fetches this once and
    derives both instead of querying pickker_orders twice."""
    resp = (
        get_client()
        .table('pickker_orders')
        .select('id, status, delivery_date, delivery_time_slot')
        .eq('customer_id', customer_id)
        .execute()
    )
    return resp.data


def get_order_ids_for_picker(picker_id):
    resp = get_client().table('pickker_orders').select('id').eq('picker_id', picker_id).execute()
    return [row['id'] for row in resp.data]


def create_order_and_items(customer_id, picker_id, address, lat, lng, picker_lat, picker_lng,
                            distance_km, items, subtotal, delivery_fee, picking_fee,
                            delivery_date, delivery_time_slot, is_quick=False, truck_type_id=None,
                            route_surface_label=None, route_paved_pct=None, eta_traffic_min=None,
                            package_fee=0, pickup_distance_km=None, delivery_distance_km=None,
                            company_id=None, account_type='b2c'):
    """Creates the order + order_items rows — the single source of truth for
    how an order gets written to the DB, used by both the real checkout flow
    (market/views.py:_create_order_and_finish) and the chat assistant's
    "schedule it for me" shortcut (market/chat_checkout.py), so both paths
    price/fee an order identically and never drift apart. Returns
    (order, order_items_rows). company_id + a None picker_id together mean
    "this order was routed to a fleet company that hasn't assigned a
    specific driver yet" — see market/fleet.py::assign_driver_to_order.
    account_type defaults to 'b2c' (matching the DB column's own default)
    since chat's B2B path already refuses vendor-fleet/truck carts and
    every other chat order really is a plain B2C one — only the real web
    checkout (which can produce genuine B2B orders) needs to pass this
    explicitly."""
    total = subtotal + delivery_fee + picking_fee + package_fee
    client = get_client()
    order_row = {
        'customer_id': customer_id,
        'picker_id': picker_id,
        'company_id': company_id,
        'account_type': account_type,
        'delivery_address': address,
        'delivery_lat': lat,
        'delivery_lng': lng,
        'picker_location_lat': picker_lat,
        'picker_location_lng': picker_lng,
        'distance_km': distance_km,
        'pickup_distance_km': pickup_distance_km,
        'delivery_distance_km': delivery_distance_km,
        'items_subtotal': str(subtotal),
        'delivery_fee': str(delivery_fee),
        'picking_fee': str(picking_fee),
        'package_fee': str(package_fee),
        'total_amount': str(total),
        'delivery_date': delivery_date,
        'delivery_time_slot': delivery_time_slot,
        'is_quick': is_quick,
        'status': 'pending_payment',
        'route_surface_label': route_surface_label,
        'route_paved_pct': route_paved_pct,
        'eta_traffic_min': eta_traffic_min,
        'truck_type_id': truck_type_id,
    }
    order_resp = client.table('pickker_orders').insert(order_row).execute()
    order = order_resp.data[0]

    order_items_rows = [
        {
            'order_id': order['id'],
            'product_id': item['product']['id'],
            'product_name': item['product']['name'],
            'unit_price': str(item['unit_price']),
            'quantity': item['quantity'],
            'line_total': str(item['line_total']),
            'measure_type': item['measure']['measure_type'] if item['measure'] else None,
            'measure_label': item['measure_label'],
            'unit': item['product']['unit'],
            'kg_equivalent': str(item['weight_kg'] / item['quantity']) if item['quantity'] else None,
        }
        for item in items
    ]
    if order_items_rows:
        client.table('pickker_order_items').insert(order_items_rows).execute()

    # Snapshot which market(s), if any, this order needs a direct shop
    # payment for (see market/shop_payments.py) — a plain generic order
    # (no item tied to a specific market) gets no rows here at all, and
    # nothing about it changes.
    from .shop_payments import record_required_markets
    required_market_ids = {item['product'].get('market_id') for item in items if item['product'].get('market_id')}
    record_required_markets(order['id'], required_market_ids)

    return order, order_items_rows
