import assert from "node:assert/strict";
import test from "node:test";
import { mergePlaybackProgress } from "../../lib/domain/progress.ts";

const current = {
  bookId: "book-1",
  chapterId: "chapter-2",
  segmentId: "segment-5",
  offsetMs: 2400,
  playbackRate: 1,
  updatedAt: "2026-08-12T08:00:00.000Z",
};

test("uses last-write-wins for cross-device playback progress", () => {
  const older = { ...current, segmentId: "segment-3", updatedAt: "2026-08-12T07:59:59.000Z" };
  const newer = { ...current, segmentId: "segment-8", offsetMs: 120, playbackRate: 1.5, updatedAt: "2026-08-12T08:01:00.000Z" };

  assert.deepEqual(mergePlaybackProgress(current, older), current);
  assert.deepEqual(mergePlaybackProgress(current, newer), newer);
});

test("sanitizes impossible offsets and playback rates before saving", () => {
  const incoming = { ...current, offsetMs: -10, playbackRate: 9, updatedAt: "2026-08-12T09:00:00.000Z" };
  assert.deepEqual(mergePlaybackProgress(current, incoming), {
    ...incoming,
    offsetMs: 0,
    playbackRate: 3,
  });
});
