export type CompoundFrequency = "monthly" | "quarterly" | "yearly";

export function compoundInterest(args: {
  principalMinor: number;
  monthlyContributionMinor: number;
  annualRate: number;
  months: number;
  frequency?: CompoundFrequency;
}): { finalMinor: number; series: { month: number; balanceMinor: number; contributedMinor: number; interestMinor: number }[] } {
  const { principalMinor, monthlyContributionMinor, annualRate, months } = args;
  const r = annualRate / 12;
  let balance = principalMinor;
  let contributed = principalMinor;
  let interest = 0;
  const series: { month: number; balanceMinor: number; contributedMinor: number; interestMinor: number }[] = [];

  for (let m = 1; m <= months; m++) {
    const monthlyInterest = Math.round(balance * r);
    interest += monthlyInterest;
    balance += monthlyInterest + monthlyContributionMinor;
    contributed += monthlyContributionMinor;
    series.push({
      month: m,
      balanceMinor: balance,
      contributedMinor: contributed,
      interestMinor: interest,
    });
  }
  return { finalMinor: balance, series };
}

export function monthsToReachGoal(args: {
  principalMinor: number;
  monthlyContributionMinor: number;
  annualRate: number;
  goalMinor: number;
  cap?: number;
}): number | null {
  const cap = args.cap ?? 1200;
  const r = args.annualRate / 12;
  let balance = args.principalMinor;
  for (let m = 1; m <= cap; m++) {
    balance += Math.round(balance * r) + args.monthlyContributionMinor;
    if (balance >= args.goalMinor) return m;
  }
  return null;
}
