import{AdjustmentType as e}from"../types.js";let parseNumber=e=>{let{value:t,defaultValue:l=0}=e;return"string"==typeof t?parseFloat(t)||l:"number"==typeof t?t:l},isValidPositiveNumber=e=>{let{value:t}=e;return!isNaN(t)&&t>0},findPolicyWithoutAfterCycle=e=>{let{policies:t}=e,l=t.filter(e=>null!=e);if(0===l.length)return null;let r=l.find(e=>{let t=e.AfterCycle??e.afterCycle;return null==t||0===t});return r??l[0]??null},calculateResult=t=>{let{variantPrice:l,adjustmentType:r,adjustmentValue:u}=t;if(!r||!u)return l;if(r===e.FIXED_AMOUNT&&u.amount){let e=parseNumber({value:u.amount});return isValidPositiveNumber({value:e})?l-e:l}if(r===e.PERCENTAGE&&void 0!==u.percentage){let e=u.percentage;return isValidPositiveNumber({value:e})?l-l*e/100:l}if(r===e.PRICE&&u.amount){let e=parseNumber({value:u.amount});return isValidPositiveNumber({value:e})?e:l}return l},parsePercentageFromName=e=>{if(!e)return null;let t=e.match(/(\d+(?:\.\d+)?)\s*%/);if(t&&t[1]){let e=parseFloat(t[1]);if(!isNaN(e)&&e>0&&e<=100)return e}return null},calculatePlanResultFromPercentage=(t,l)=>calculateResult({variantPrice:t,adjustmentType:e.PERCENTAGE,adjustmentValue:{percentage:l}}),calculatePlanResult=e=>{let{plan:t,variantPrice:l}=e,r=t.pricingPolicies;if(Array.isArray(r)&&r.length>0){let e=r.filter(e=>null!=e);if(e.length>0){let t=findPolicyWithoutAfterCycle({policies:e});if(t){let e=t.AdjustmentType??t.adjustmentType,r=t.AdjustmentValue??t.adjustmentValue;return calculateResult({variantPrice:l,adjustmentType:e,adjustmentValue:r})}}}let u=parsePercentageFromName(t.name);return null!==u?calculatePlanResultFromPercentage(l,u):l},findBestPlanFromList=e=>{let{plans:t,variantPrice:l}=e;if(0===t.length)return null;let r=null,u=1/0;for(let e of t){let t=calculatePlanResult({plan:e,variantPrice:l});if(t<u)u=t,r=e;else if(t===u&&r){let t=e=>{let t=e.updatedAt;if(!t)return 0;if("string"==typeof t){let e=Date.parse(t);return isNaN(e)?parseFloat(t)||0:e}return t},l=t(e),u=t(r);l>u?r=e:l===u&&e.id>r.id&&(r=e)}}return r};export{findBestPlanFromList};
