// Projection / annual extrapolation (KAR-840, V11 section 5 — buildProjection
// + projTotals). Deterministic: gross = Δ/unit × volume; the defend quota
// (Abwehrquote) reduces only cost INCREASES (V11 gross>0 guard) — savings are
// never "defended away". Editable state (years, volumes, override, quota)
// lives in the client component; this module is pure math.

export interface ProjectionYearInput {
  year: number
  volume: number
  included: boolean
}

export interface ProjectionYear extends ProjectionYearInput {
  gross: number
  defended: number
  remaining: number
  /** Running sum of remaining over included years (chart line). */
  cumRemaining: number
}

export interface ProjectionTotals {
  vol: number
  gross: number
  defended: number
  remaining: number
  nYears: number
}

export interface Projection {
  perYear: ProjectionYear[]
  totals: ProjectionTotals
}

/** V11 manual mode: n years from startYear, volume 0, all included. */
export function defaultProjectionYears(startYear: number, n = 5): ProjectionYearInput[] {
  return Array.from({ length: n }, (_, i) => ({ year: startYear + i, volume: 0, included: true }))
}

export function computeProjection(
  years: ProjectionYearInput[],
  deltaPerUnit: number,
  defendPct: number,
): Projection {
  let cum = 0
  const perYear: ProjectionYear[] = years.map((y) => {
    const active = y.included ? y.volume || 0 : 0
    const gross = deltaPerUnit * active
    const defended = gross > 0 ? gross * defendPct : 0
    const remaining = gross - defended
    cum += remaining
    return { ...y, gross, defended, remaining, cumRemaining: cum }
  })

  // Totals derived from the per-year rows — one formula, no desync risk.
  const included = perYear.filter((y) => y.included)
  return {
    perYear,
    totals: {
      vol: included.reduce((s, y) => s + (y.volume || 0), 0),
      gross: included.reduce((s, y) => s + y.gross, 0),
      defended: included.reduce((s, y) => s + y.defended, 0),
      remaining: included.reduce((s, y) => s + y.remaining, 0),
      nYears: included.length,
    },
  }
}
