"""Admin-registered alternative ways a product can be sold — kg, bucket,
sack, sadolin (tin), or by the piece. Each measure has its own admin-set
price (vendors quote a price per container directly, not a weight-derived
one) and a separate kg-equivalent used only to compute the picking fee's
weight tier. A product with no rows here just keeps behaving as it always
has (its plain `unit`/`market_price`). Measures are soft-toggled active/
inactive, never deleted, so a past order's snapshot of the measure it used
stays meaningful even after an admin changes the catalog."""

from accounts.supabase_client import get_client

# The catalog of measure types (kg/bucket/sack/sadolin/piece and whatever
# else an admin has registered) now lives in market/measure_units.py —
# see get_active_measure_units()/get_unit_label_map() there.


def get_measures_for_product(product_id):
    resp = (
        get_client()
        .table('pickker_product_measures')
        .select('*')
        .eq('product_id', product_id)
        .order('measure_type')
        .execute()
    )
    return resp.data


def get_active_measures_for_product(product_id):
    return [m for m in get_measures_for_product(product_id) if m['is_active']]


def get_active_measures_for_products(product_ids):
    """Batched version for a whole product list — one query instead of one
    per product (see the market-page N+1 note in price_trends.py for why
    this matters). Returns {product_id: [measure, ...]}."""
    product_ids = list(product_ids)
    if not product_ids:
        return {}
    resp = (
        get_client()
        .table('pickker_product_measures')
        .select('*')
        .in_('product_id', product_ids)
        .eq('is_active', True)
        .order('measure_type')
        .execute()
    )
    by_product = {pid: [] for pid in product_ids}
    for row in resp.data:
        by_product.setdefault(row['product_id'], []).append(row)
    return by_product


def get_measure_min_qty(measure):
    """Admin-editable minimum quantity of this measure a customer must order
    per line (e.g. at least 2 buckets) — independent of the product's own
    min_purchase_qty, since a measure is priced and ordered on its own
    terms. Defaults to 1 (no restriction)."""
    return int((measure or {}).get('min_qty') or 1)


def save_measure(product_id, measure_type, price, kg_equivalent, is_default=False, min_qty=1):
    client = get_client()
    if is_default:
        # Only one default measure per product.
        client.table('pickker_product_measures').update({'is_default': False}).eq('product_id', product_id).execute()

    existing = (
        client.table('pickker_product_measures')
        .select('id')
        .eq('product_id', product_id)
        .eq('measure_type', measure_type)
        .execute()
    )
    row = {
        'price': str(price),
        'kg_equivalent': str(kg_equivalent),
        'is_default': is_default,
        'is_active': True,
        'min_qty': min_qty,
    }
    if existing.data:
        client.table('pickker_product_measures').update(row).eq('id', existing.data[0]['id']).execute()
    else:
        row.update({'product_id': product_id, 'measure_type': measure_type})
        client.table('pickker_product_measures').insert(row).execute()


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

def deactivate_measure(product_id, measure_type):
    client = get_client()
    client.table('pickker_product_measures').update({
        'is_active': False,
        'is_default': False
    }).eq('product_id', product_id).eq('measure_type', measure_type).execute()
