import type { PlaybackProgress } from "./types";

function sanitize(progress: PlaybackProgress): PlaybackProgress {
  const offsetMs = Number.isFinite(progress.offsetMs)
    ? Math.max(0, Math.round(progress.offsetMs))
    : 0;
  const playbackRate = Number.isFinite(progress.playbackRate)
    ? Math.min(3, Math.max(0.5, progress.playbackRate))
    : 1;
  return { ...progress, offsetMs, playbackRate };
}

export function mergePlaybackProgress(
  current: PlaybackProgress | null,
  incoming: PlaybackProgress,
): PlaybackProgress {
  const candidate = sanitize(incoming);
  if (!current) return candidate;

  const currentTime = Date.parse(current.updatedAt);
  const incomingTime = Date.parse(candidate.updatedAt);
  if (!Number.isFinite(incomingTime)) return sanitize(current);
  if (!Number.isFinite(currentTime) || incomingTime >= currentTime) return candidate;
  return sanitize(current);
}
