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