import { afterEach, describe, expect, it, vi } from "vitest";

import { GenerationPollingLoop } from "../../apps/worker/src/generation-polling-loop.js";

describe("POSTV1-05 generation polling loop", () => {
  afterEach(() => {
    vi.useRealTimers();
  });

  it("does not start another processor call while the current call is unresolved", async () => {
    vi.useFakeTimers();
    let finishCurrentCall: (() => void) | undefined;
    const processNext = vi.fn(() => new Promise<void>((resolve) => {
      finishCurrentCall = resolve;
    }));
    const loop = new GenerationPollingLoop({ processNext }, 250);

    await vi.advanceTimersByTimeAsync(1_000);
    expect(processNext).toHaveBeenCalledTimes(1);

    finishCurrentCall?.();
    await Promise.resolve();
    await vi.advanceTimersByTimeAsync(250);
    expect(processNext).toHaveBeenCalledTimes(2);

    loop.close();
  });
});
