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

test("reports stored and pending usage and reserves pending uploads at the 8 GB soft limit", async () => {
  const { d1, database } = await createTestD1();
  database.exec(`
    INSERT INTO books (id, title, format, source_object_key, source_bytes)
    VALUES ('b1', 'Book', 'pdf', 'source.pdf', 100);
    INSERT INTO storage_ledger (object_key, kind, book_id, bytes)
    VALUES ('source.pdf', 'source', 'b1', 100);
    INSERT INTO storage_ledger (object_key, kind, book_id, bytes)
    VALUES ('audio.mp3', 'audio', 'b1', 50);
    INSERT INTO upload_sessions (
      id, r2_upload_id, object_key, file_name, mime_type, format,
      total_bytes, part_size, part_count, uploaded_parts_json, status,
      expires_at, created_at, updated_at
    ) VALUES (
      'uploading', 'r2-uploading', 'sources/uploading/book.pdf', 'book.pdf',
      'application/pdf', 'pdf', 25, 8388608, 1, '[]', 'uploading',
      '2026-08-19T00:00:00.000Z', '2026-08-12T00:00:00.000Z',
      '2026-08-12T00:00:00.000Z'
    );
  `);

  const repository = new StorageRepository(d1);
  assert.deepEqual(await repository.usage(), {
    usedBytes: 150,
    sourceBytes: 100,
    audioBytes: 50,
    pendingUploadBytes: 25,
    softLimitBytes: 8 * 1024 ** 3,
  });
  await repository.assertSourceAdmission(8 * 1024 ** 3 - 175);
  await assert.rejects(
    repository.assertSourceAdmission(8 * 1024 ** 3 - 174),
    /8 GB/,
  );
});
