/**
 * nii-estimate.ts — NII marginal-banding contribution estimator.
 *
 * Proper marginal banding for self-employed NII (2026+ rates).
 * Rates and thresholds are loaded per-year from KV: nii_rates:{year}.
 * Never hard-code rates here.
 *
 * Spec: 2026-06-01-bituach-leumi (spec 175, wave-15)
 */
import type { NIIRates, NIIEstimate } from '@zync/types'

/**
 * Estimate annual NII contributions (national insurance + health insurance)
 * for a self-employed individual with the given annual net income.
 *
 * Uses marginal banding:
 *  - Reduced rate on monthly income up to band1_monthly_ils
 *  - Full rate on monthly income from band1_monthly_ils to income_cap_monthly_ils
 *  - Income above the cap is not charged
 */
export function estimateNIIContributions(annualNetIncome: number, rates: NIIRates): NIIEstimate {
  const monthlyIncome = Math.max(0, annualNetIncome) / 12

  const band1 = rates.band1_monthly_ils         // ≈ 6,331 (60% of average wage)
  const cap   = rates.income_cap_monthly_ils    // ≈ 45,075 (income cap)
  const reducedRate = rates.reduced_rate        // 0.0597
  const fullRate    = rates.full_rate           // 0.1783

  // Marginal banding on monthly income, then annualise
  const inReduced = Math.min(monthlyIncome, band1)
  const inFull    = Math.max(0, Math.min(monthlyIncome, cap) - band1)
  // Income above the cap is not charged

  const monthlyContribution = inReduced * reducedRate + inFull * fullRate
  const total = Math.round(monthlyContribution * 12)

  // The combined rate includes health insurance; split proportionally for display
  const healthInsurance = Math.round(total * (rates.health_share ?? 0))

  return {
    national_insurance: total - healthInsurance,
    health_insurance: healthInsurance,
    total,
  }
}
