// Auto-manage shopping list when item quantity changes relative to min_stock_threshold
onRecordAfterUpdateSuccess((e) => {
  const item = e.record;
  const qty = item.getFloat('quantity');
  const minStock = item.getFloat('min_stock_threshold');

  if (!minStock || minStock === 0) return;

  const householdId = item.getString('household');
  const app = e.app;

  const existing = app.findRecordsByFilter(
    'shopping_list',
    `item_id = "${item.id}" && is_checked = false`,
    '',
    1,
    0
  );

  if (qty <= minStock && existing.length === 0) {
    const col = app.findCollectionByNameOrId('shopping_list');
    const entry = new Record(col);
    entry.set('household', householdId);
    entry.set('item_id', item.id);
    entry.set('name', item.getString('name'));
    entry.set('suggested_quantity', minStock - qty + 1);
    entry.set('unit', item.getString('unit'));
    entry.set('is_checked', false);
    entry.set('auto_added', true);
    app.save(entry);

    if (!item.getBool('on_shopping_list')) {
      item.set('on_shopping_list', true);
      app.save(item);
    }
  } else if (qty > minStock && existing.length > 0) {
    app.delete(existing[0]);

    if (item.getBool('on_shopping_list')) {
      item.set('on_shopping_list', false);
      app.save(item);
    }
  }
}, 'items');
