// ── Observed-CT auto-sum ──────────────────────────────────────────────────────
// Pure logic for deriving the observed cycle time from its sub-times
// (machine / value-add / non-VA / load-unload). Used by the Workshop-Erfassung
// client; extracted for testability.

export interface SubTimes {
  machine_time_sec: number | null
  value_add_time_sec: number | null
  non_va_time_sec: number | null
  load_unload_time_sec: number | null
}

/** Sum of all sub-times, treating null as 0. */
export function subTimeSum(t: SubTimes): number {
  return (
    (t.machine_time_sec ?? 0) +
    (t.value_add_time_sec ?? 0) +
    (t.non_va_time_sec ?? 0) +
    (t.load_unload_time_sec ?? 0)
  )
}

/**
 * Observed CT after a sub-time edit.
 *
 * Auto-follows the sub-time sum while the observed CT is unset or still equals
 * the previous auto-computed sum. A manually diverging value is never
 * overwritten — "auto-set" is detected by value equality with the previous
 * sum, so no extra per-step state is needed.
 */
export function nextObservedCt(
  currentObservedCt: number | null,
  prevTimes: SubTimes,
  nextTimes: SubTimes,
): number | null {
  const nextSum = subTimeSum(nextTimes)
  if (nextSum <= 0) return currentObservedCt
  const wasAutoSet =
    currentObservedCt == null || currentObservedCt === subTimeSum(prevTimes)
  return wasAutoSet ? nextSum : currentObservedCt
}
