/**
 * Time rounding utilities — time-management.
 *
 * `roundDuration` applies the tenant's configured rounding mode to raw elapsed
 * seconds. The rounded value is stored in `time_entries.duration_seconds`; the
 * raw start/stop timestamps are preserved for audit.
 */
import type { TimeRoundingMode } from '@zync/types'

/**
 * Round a raw duration (in seconds) according to the given mode.
 *
 * @example
 * roundDuration(520, 'up_15')      // 900  (rounds up to 15 min)
 * roundDuration(520, 'nearest_15') // 600  (8m40s → nearest 15min = 0min → 600s)
 * roundDuration(520, 'none')       // 520  (no rounding)
 */
export function roundDuration(durationSeconds: number, mode: TimeRoundingMode): number {
  if (mode === 'none') return durationSeconds

  const minuteMap: Record<Exclude<TimeRoundingMode, 'none'>, number> = {
    nearest_5: 5,
    nearest_15: 15,
    nearest_30: 30,
    up_15: 15,
    up_30: 30,
  }
  const interval = minuteMap[mode] * 60 // convert to seconds

  if (mode.startsWith('nearest_')) {
    return Math.round(durationSeconds / interval) * interval
  }
  // 'up_*' modes: always round up
  return Math.ceil(durationSeconds / interval) * interval
}
