import{getPerBundleQuantity}from"./line-items";export const getBundleComponentVariants=(t,i=[])=>{const n={};return(i||[]).forEach((i=>{var e,o,l;if((null==i?void 0:i.bundle_line_item)!==t)return;const d=null===(o=null===(e=null==i?void 0:i.price)||void 0===e?void 0:e.product)||void 0===o?void 0:o.id,a=null===(l=null==i?void 0:i.variant)||void 0===l?void 0:l.id;d&&a&&(n[d]=a)})),n};export const getAvailableStock=t=>{var i,n,e;const o=null===(i=null==t?void 0:t.price)||void 0===i?void 0:i.product,l=(null===(n=null==t?void 0:t.variant)||void 0===n?void 0:n.id)?null===(e=null==t?void 0:t.variant)||void 0===e?void 0:e.available_stock:null==o?void 0:o.available_stock;return Math.max(Number(l)||0,0)};export const getOutOfStockLineItems=(t=[])=>(t||[]).filter((t=>"out_of_stock"===(null==t?void 0:t.purchasable_status)&&getAvailableStock(t)<t.quantity));export const getBundleQuantityReductions=(t=[],i=new Map)=>{const n=new Map;return getOutOfStockLineItems(t).forEach((e=>{var o,l,d,a;if(!e.component_line_item||!e.bundle_line_item)return;const u=(t||[]).find((t=>t.id===e.bundle_line_item));if(!(null==u?void 0:u.id))return;const r=null===(l=null===(o=e.price)||void 0===o?void 0:o.product)||void 0===l?void 0:l.id;if(r&&(null===(d=i.get(u.id))||void 0===d?void 0:d.has(r)))return;const v=getPerBundleQuantity(e,u.quantity),c=Math.floor(getAvailableStock(e)/v),s=null!==(a=n.get(u.id))&&void 0!==a?a:u.quantity;n.set(u.id,Math.max(Math.min(s,c),0))})),n};export const buildStockAdjustedLineItems=(t=[],i=new Map)=>{const n=new Map(Array.from(i,(([t,i])=>[t,new Set(Object.keys(i))]))),e=getBundleQuantityReductions(t,n),o=new Map;return getOutOfStockLineItems(t).forEach((t=>{!t.component_line_item&&t.id&&o.set(t.id,getAvailableStock(t))})),(t||[]).filter((t=>!t.component_line_item)).map((t=>{var n,l,d,a;const u=t.id,r=!!u&&i.has(u);let v=t.quantity;return u&&e.has(u)?v=null!==(n=e.get(u))&&void 0!==n?n:v:u&&o.has(u)&&(v=null!==(l=o.get(u))&&void 0!==l?l:v),{id:u,price_id:null===(d=t.price)||void 0===d?void 0:d.id,quantity:v,...(null===(a=null==t?void 0:t.variant)||void 0===a?void 0:a.id)?{variant:t.variant.id}:{},...u&&r?{bundle_component_variants:i.get(u)}:{}}}))};export const buildStockAlertRows=(t=[])=>{const i=getBundleQuantityReductions(t),n=new Set,e=[];return getOutOfStockLineItems(t).forEach((o=>{var l,d,a;if(o.component_line_item&&o.bundle_line_item){const a=(t||[]).find((t=>t.id===o.bundle_line_item));if(!(null==a?void 0:a.id)||n.has(a.id))return;n.add(a.id);const u=null===(l=a.price)||void 0===l?void 0:l.product;return void e.push({name:null==u?void 0:u.name,variant:null==a?void 0:a.variant_display_options,image:null==a?void 0:a.image,from:a.quantity,to:Math.max(null!==(d=i.get(a.id))&&void 0!==d?d:a.quantity,0)})}const u=null===(a=o.price)||void 0===a?void 0:a.product;e.push({name:null==u?void 0:u.name,variant:null==o?void 0:o.variant_display_options,image:null==o?void 0:o.image,from:o.quantity,to:getAvailableStock(o)})})),e};