"use strict";var types=require("../types.js");const 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=e=>{let{variantPrice:t,adjustmentType:l,adjustmentValue:r}=e;if(!l||!r)return t;if(l===types.AdjustmentType.FIXED_AMOUNT&&r.amount){let e=parseNumber({value:r.amount});return isValidPositiveNumber({value:e})?t-e:t}if(l===types.AdjustmentType.PERCENTAGE&&void 0!==r.percentage){let e=r.percentage;return isValidPositiveNumber({value:e})?t-t*e/100:t}if(l===types.AdjustmentType.PRICE&&r.amount){let e=parseNumber({value:r.amount});return isValidPositiveNumber({value:e})?e:t}return t},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=(e,t)=>calculateResult({variantPrice:e,adjustmentType:types.AdjustmentType.PERCENTAGE,adjustmentValue:{percentage:t}}),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};exports.findBestPlanFromList=findBestPlanFromList;
