import assert from "node:assert/strict";
import test from "node:test";
import { ProgressOutbox, progressOutboxKey } from "../../lib/client/player/progress-outbox.ts";

class MemoryStorage {
  values = new Map();
  getItem(key) { return this.values.get(key) ?? null; }
  setItem(key, value) { this.values.set(key, value); }
  removeItem(key) { this.values.delete(key); }
}

const progress = {
  chapterId: "c1", segmentId: "s1", offsetMs: 1200,
  playbackRate: 1.25, updatedAt: "2026-08-13T06:00:00.000Z",
};

test("keeps the newest unsent progress per book and clears it after sync", () => {
  const storage = new MemoryStorage();
  const outbox = new ProgressOutbox(storage);
  assert.equal(progressOutboxKey("book/1"), "hearbooks:progress:book%2F1");
  outbox.save("book/1", progress);
  outbox.save("book/1", { ...progress, offsetMs: 100, updatedAt: "2026-08-13T05:59:00.000Z" });
  assert.deepEqual(outbox.get("book/1"), progress);
  outbox.clear("book/1", progress.updatedAt);
  assert.equal(outbox.get("book/1"), null);
});

test("ignores malformed local values and does not clear a newer pending write", () => {
  const storage = new MemoryStorage();
  const outbox = new ProgressOutbox(storage);
  storage.setItem(progressOutboxKey("b1"), "not-json");
  assert.equal(outbox.get("b1"), null);
  outbox.save("b1", progress);
  outbox.clear("b1", "2026-08-13T05:00:00.000Z");
  assert.deepEqual(outbox.get("b1"), progress);
});
