import { afterEach, describe, expect, it, vi } from "vitest";
import { createTelegramTypingLease } from "./runtime-telegram-typing.js";
import {
  expectBackgroundTypingPulseFailuresAreSwallowed,
  expectIndependentTypingLeases,
} from "./typing-lease.test-support.js";

describe("createTelegramTypingLease", () => {
  afterEach(() => {
    vi.useRealTimers();
  });

  it("pulses immediately and keeps leases independent", async () => {
    await expectIndependentTypingLeases({
      createLease: createTelegramTypingLease,
      buildParams: (pulse) => ({
        to: "telegram:123",
        intervalMs: 2_000,
        pulse,
      }),
    });
  });

  it("swallows background pulse failures", async () => {
    const pulse = vi
      .fn<
        (params: {
          to: string;
          accountId?: string;
          cfg?: unknown;
          messageThreadId?: number;
        }) => Promise<unknown>
      >()
      .mockResolvedValueOnce(undefined)
      .mockRejectedValueOnce(new Error("boom"));

    await expectBackgroundTypingPulseFailuresAreSwallowed({
      createLease: createTelegramTypingLease,
      pulse,
      buildParams: (pulse) => ({
        to: "telegram:123",
        intervalMs: 2_000,
        pulse,
      }),
    });
  });

  it("falls back to the default interval for non-finite values", async () => {
    vi.useFakeTimers();
    const pulse = vi.fn(async () => undefined);

    const lease = await createTelegramTypingLease({
      to: "telegram:123",
      intervalMs: Number.NaN,
      pulse,
    });

    expect(pulse).toHaveBeenCalledTimes(1);
    await vi.advanceTimersByTimeAsync(3_999);
    expect(pulse).toHaveBeenCalledTimes(1);
    await vi.advanceTimersByTimeAsync(1);
    expect(pulse).toHaveBeenCalledTimes(2);

    lease.stop();
  });
});
