import assert from "node:assert/strict";
import test from "node:test";
import { ProgressRepository } from "../../lib/server/repositories/progress.ts";
import { createTestD1 } from "../helpers/sqlite-d1.mjs";

function seed(database) {
  database.exec(`
    INSERT INTO books (id, title, format, source_object_key, source_bytes, status)
      VALUES ('book-1', '书', 'epub', 'sources/book.epub', 10, 'ready');
    INSERT INTO chapters (id, book_id, title, position) VALUES ('chapter-1', 'book-1', '第一章', 0);
    INSERT INTO segments (id, chapter_id, position, text, language, content_hash)
      VALUES ('segment-1', 'chapter-1', 0, '一句。', 'zh-CN', '${"a".repeat(64)}');
  `);
}

test("saves a valid last position and ignores an older device write", async () => {
  const { d1, database } = await createTestD1();
  seed(database);
  const repository = new ProgressRepository(d1);
  const current = await repository.save("book-1", {
    chapterId: "chapter-1", segmentId: "segment-1", offsetMs: 2500,
    playbackRate: 1.25, updatedAt: "2026-08-13T05:00:00.000Z",
  });
  const older = await repository.save("book-1", {
    chapterId: "chapter-1", segmentId: "segment-1", offsetMs: 100,
    playbackRate: 1, updatedAt: "2026-08-13T04:00:00.000Z",
  });
  assert.deepEqual(older, current);
  assert.deepEqual(await repository.get("book-1"), current);
  assert.equal(database.prepare("SELECT last_listened_at FROM books WHERE id = 'book-1'").get().last_listened_at, current.updatedAt);
});

test("rejects cross-book chapter or segment ids", async () => {
  const { d1, database } = await createTestD1();
  seed(database);
  database.exec(`
    INSERT INTO books (id, title, format, source_object_key, source_bytes) VALUES ('book-2', '书2', 'pdf', 'sources/2.pdf', 10);
    INSERT INTO chapters (id, book_id, title, position) VALUES ('chapter-2', 'book-2', '第二章', 0);
    INSERT INTO segments (id, chapter_id, position, text, language, content_hash)
      VALUES ('segment-2', 'chapter-2', 0, 'Two.', 'en-US', '${"b".repeat(64)}');
  `);
  const repository = new ProgressRepository(d1);
  await assert.rejects(repository.save("book-1", {
    chapterId: "chapter-2", segmentId: "segment-2", offsetMs: 0,
    playbackRate: 1, updatedAt: "2026-08-13T05:00:00.000Z",
  }), /不属于/);
});
