import { type LoanOffer } from '../types';

export const computePlanTotalsFromMultiplier = (
  amountMxn: number,
  totalMultiplier: number,
  weeks: number,
): { total: number; weekly: number } => {
  const total = Math.round(amountMxn * totalMultiplier * 100) / 100;
  const weekly = Math.round((total / weeks) * 100) / 100;
  return { total, weekly };
};

export const isAmountWithinOfferBounds = (
  offer: LoanOffer,
  amountMxn: number,
): boolean =>
  amountMxn >= offer.minAmountMxn && amountMxn <= offer.preApprovedMaxAmountMxn;

function computeMinInstallmentWeeksFromCap(
  amountMxn: number,
  maxInstallmentAmountMxn: number,
): number {
  if (maxInstallmentAmountMxn <= 0) {
    return 1;
  }
  return Math.ceil(amountMxn / maxInstallmentAmountMxn);
}

export const getEligiblePlanWeeks = (
  offer: LoanOffer,
  amountMxn: number,
): number[] => {
  if (!isAmountWithinOfferBounds(offer, amountMxn)) {
    return [];
  }

  let eligibleOptions = [...offer.planOptions];
  const cap = offer.maxInstallmentAmountMxn;
  if (cap !== undefined && cap > 0) {
    const minWeeks = computeMinInstallmentWeeksFromCap(amountMxn, cap);
    eligibleOptions = eligibleOptions.filter(
      option => option.weeks >= minWeeks,
    );
  }

  return eligibleOptions.map(o => o.weeks);
};
