import assert from "node:assert/strict";
import test from "node:test";
import { UploadCheckpointStore, fileCheckpointKey } from "../../lib/client/upload-checkpoints.ts";

class MemoryBackend {
  values = new Map();
  async get(key) { return this.values.get(key); }
  async put(value, key) { this.values.set(key, structuredClone(value)); }
  async delete(key) { this.values.delete(key); }
}

test("uses file identity to restore an unfinished upload across refreshes", async () => {
  const backend = new MemoryBackend();
  const store = new UploadCheckpointStore(
    backend,
    () => new Date("2026-08-19T00:00:00.000Z"),
  );
  const file = { name: "book.pdf", size: 123, lastModified: 99 };
  assert.equal(fileCheckpointKey(file), "book.pdf::123::99");
  await store.save(file, { uploadId: "u1", expiresAt: "2026-08-20T00:00:00.000Z" });
  assert.deepEqual(await store.get(file), { uploadId: "u1", expiresAt: "2026-08-20T00:00:00.000Z" });
  await store.clear(file);
  assert.equal(await store.get(file), null);
});

test("drops expired checkpoints instead of attempting a closed upload", async () => {
  const backend = new MemoryBackend();
  const store = new UploadCheckpointStore(backend, () => new Date("2026-08-21T00:00:00.000Z"));
  const file = { name: "book.epub", size: 5, lastModified: 1 };
  await store.save(file, { uploadId: "old", expiresAt: "2026-08-20T00:00:00.000Z" });
  assert.equal(await store.get(file), null);
  assert.equal(backend.values.size, 0);
});
