import { createTileSnapshotScheduler } from "./tileSnapshotScheduler";

describe("createTileSnapshotScheduler", () => {
  beforeEach(() => {
    jest.useFakeTimers();
  });

  afterEach(() => {
    jest.useRealTimers();
  });

  it("defers and coalesces tile snapshots until movement ends", () => {
    const publish = jest.fn();
    const scheduler = createTileSnapshotScheduler({ publish, wait: 50 });

    scheduler.beginMove();
    scheduler.markDirty();
    scheduler.markDirty();
    jest.advanceTimersByTime(100);
    expect(publish).not.toHaveBeenCalled();

    scheduler.endMove();
    jest.advanceTimersByTime(49);
    expect(publish).not.toHaveBeenCalled();
    jest.advanceTimersByTime(1);
    expect(publish).toHaveBeenCalledTimes(1);
  });

  it("batches settled tile arrivals and cancels pending work", () => {
    const publish = jest.fn();
    const scheduler = createTileSnapshotScheduler({ publish, wait: 50 });

    scheduler.markDirty();
    jest.advanceTimersByTime(25);
    scheduler.markDirty();
    jest.advanceTimersByTime(49);
    expect(publish).not.toHaveBeenCalled();
    jest.advanceTimersByTime(1);
    expect(publish).toHaveBeenCalledTimes(1);

    scheduler.markDirty();
    scheduler.cancel();
    jest.runAllTimers();
    expect(publish).toHaveBeenCalledTimes(1);
  });
});
