import { expect, test } from "bun:test";
import { createFileStreamReceiver, databaseChangeFeed, frameFileStream } from "../src/index.ts";

test("database feeds publish only allowed safe table changes", async () => {
  let handler: ((change: any) => void) | undefined;
  const published: string[] = [];
  databaseChangeFeed(
    {
      subscribe(next) {
        handler = next;
        return () => {};
      },
    },
    (topic) => {
      published.push(topic);
    },
    { allowTables: ["users"] },
  );
  await handler!({ table: "users", operation: "update", occurredAt: 1 });
  await handler!({ table: "secrets", operation: "update", occurredAt: 1 });
  await handler!({ table: "users;drop", operation: "delete", occurredAt: 1 });
  expect(published).toEqual(["db:users"]);
});

test("file streams reassemble out of order and enforce bounds", () => {
  const bytes = new TextEncoder().encode("x".repeat(3000));
  const frames = frameFileStream("upload-1", bytes, { chunkBytes: 1024 });
  const receiver = createFileStreamReceiver({ maxBytes: 4000 });
  expect(receiver.accept(frames[2]!)).toBeNull();
  expect(receiver.accept(frames[0]!)).toBeNull();
  expect(receiver.accept(frames[1]!)).toEqual(bytes);
  expect(() => frameFileStream("bad/id", bytes)).toThrow("Invalid stream id");
  expect(() => frameFileStream("large", bytes, { maxBytes: 10 })).toThrow("FILE-LIMIT");
});
