import assert from "node:assert/strict";
import test from "node:test";
import { createProgressApi } from "../../lib/server/progress-api.ts";

test("returns null progress and saves only typed position fields", async () => {
  const saved = [];
  const api = createProgressApi({
    get: async () => null,
    save: async (bookId, input) => { saved.push({ bookId, ...input }); return { bookId, ...input }; },
  });
  assert.deepEqual(await (await api.get("book-1")).json(), { progress: null });
  const response = await api.put(new Request("https://example.test", {
    method: "PUT", headers: { "content-type": "application/json" },
    body: JSON.stringify({ chapterId: "c1", segmentId: "s1", offsetMs: 1200, playbackRate: 1.5, updatedAt: "2026-08-13T05:00:00.000Z", ignored: "x" }),
  }), "book-1");
  assert.equal(response.status, 200);
  assert.equal(saved[0].ignored, undefined);
});

test("rejects malformed progress", async () => {
  const api = createProgressApi({ get: async () => null, save: async () => null });
  const response = await api.put(new Request("https://example.test", {
    method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ offsetMs: -1 }),
  }), "book-1");
  assert.equal(response.status, 400);
});
