import{findBestPlanFromList as e}from"./calculateBestSellingPlan.js";import{convertDecimalToNumber as r}from"@gem-sdk/core";let DEFAULT_SOURCE_APP="__unknown__",getAllValidPlans=e=>{let r=[];for(let i of e)if(i?.sellingPlans){let e=i.sellingPlans.filter(e=>null!=e);r.push(...e)}return r},getVariantPrice=e=>{if(!e)return 0;let i="number"==typeof e.price?String(e.price):e.price??void 0;return r(i)??0},findGroupByPlanId=(e,r)=>e.find(e=>e?.sellingPlans?.some(e=>e?.baseID===r||e?.id===r)),findGroupByBestPlan=(r,i)=>{let n=getAllValidPlans(r);if(0===n.length)return;let t=e({plans:n,variantPrice:i});if(t)return findGroupByPlanId(r,t.baseID||t.id||"")},findGroupByExactMeta=({sellingPlanGroups:e,extractedSettings:r,hasGroup:i,hasSourceApp:n,isUnknownSourceApp:t})=>i?t?e.find(e=>e?.id===r.group):n?e.find(e=>e?.appID===r.sourceApp&&e?.id===r.group):void 0:void 0,findMatchedGroup=e=>{let{sellingPlanGroups:r,extractedSettings:i,currentVariant:n}=e,t=getAllValidPlans(r),l=getVariantPrice(n),p=!!i.group,o=i.sourceApp===DEFAULT_SOURCE_APP,u=!!i.sourceApp,d=findGroupByExactMeta({sellingPlanGroups:r,extractedSettings:i,hasGroup:p,hasSourceApp:u,isUnknownSourceApp:o}),a=i.defaultOptions?findGroupByPlanId(r,i.defaultOptions):void 0,f=i.sourceApp&&i.sourceApp!==DEFAULT_SOURCE_APP?r.find(e=>e?.appID===i.sourceApp):void 0,s=!p||void 0===i.sourceApp||!!d,P=!i.defaultOptions||!!a,c=!i.sourceApp||i.sourceApp===DEFAULT_SOURCE_APP||!!f,A=!(s&&P&&c);if(A){let e=findGroupByBestPlan(r,l);return e||(t.length?r[0]:void 0)}if(i.defaultOptions){let e=findGroupByPlanId(r,i.defaultOptions);if(e)return e}if(i.sourceApp){let e=r.find(e=>e?.appID===i.sourceApp);if(e)return e}if(l>0){let e=findGroupByBestPlan(r,l);if(e)return e}return r[0]};export{findMatchedGroup};
