import assert from "node:assert/strict";
import test from "node:test";
import {
  R2_SOFT_LIMIT_BYTES,
  planAudioRetention,
  planStorageAdmission,
} from "../../lib/domain/storage.ts";

const audioBooks = [1, 2, 3, 4, 5].map((day) => ({
  bookId: `book-${day}`,
  bytes: day * 100,
  lastUsedAt: `2026-08-0${day}T00:00:00.000Z`,
}));

test("keeps audio for at most the five most recently used books", () => {
  assert.deepEqual(planAudioRetention(audioBooks, "book-6"), ["book-1"]);
  assert.deepEqual(planAudioRetention(audioBooks, "book-3"), []);
  assert.deepEqual(planAudioRetention([...audioBooks, { bookId: "book-6", bytes: 1, lastUsedAt: "2026-08-06T00:00:00.000Z" }], "book-7"), ["book-1", "book-2"]);
});

test("admits data under 8 GB and proposes oldest audio cleanup before rejection", () => {
  assert.deepEqual(planStorageAdmission({ usedBytes: 1000, pendingBytes: 500, audioBooks }), {
    allowed: true,
    evictBookIds: [],
    bytesAfter: 1500,
  });

  const nearLimit = R2_SOFT_LIMIT_BYTES - 50;
  assert.deepEqual(planStorageAdmission({ usedBytes: nearLimit, pendingBytes: 120, audioBooks }), {
    allowed: true,
    evictBookIds: ["book-1"],
    bytesAfter: nearLimit + 20,
  });

  assert.deepEqual(planStorageAdmission({ usedBytes: R2_SOFT_LIMIT_BYTES, pendingBytes: R2_SOFT_LIMIT_BYTES, audioBooks: [] }), {
    allowed: false,
    evictBookIds: [],
    bytesAfter: R2_SOFT_LIMIT_BYTES * 2,
  });
});
