/**
 * Unit tests for callMiniAppReadyOnce: single-call behaviour and missing SDK.
 */

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

const isAvailableFn = vi.fn().mockReturnValue(true);

vi.mock("@telegram-apps/sdk-react", () => {
  const readyFn = vi.fn();
  return {
    miniAppReady: Object.assign(readyFn, {
      isAvailable: () => isAvailableFn(),
    }),
  };
});

describe("callMiniAppReadyOnce", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    isAvailableFn.mockReturnValue(true);
  });

  it("calls miniAppReady at most once per session", async () => {
    vi.resetModules();
    const { callMiniAppReadyOnce } = await import("./telegram-ready");
    const { miniAppReady } = await import("@telegram-apps/sdk-react");
    const readyCall = miniAppReady as ReturnType<typeof vi.fn>;

    callMiniAppReadyOnce();
    callMiniAppReadyOnce();
    expect(readyCall).toHaveBeenCalledTimes(1);
  });

  it("does not throw when SDK is unavailable", async () => {
    isAvailableFn.mockReturnValue(false);
    vi.resetModules();
    const { callMiniAppReadyOnce } = await import("./telegram-ready");

    expect(() => callMiniAppReadyOnce()).not.toThrow();
  });

  it("does not call miniAppReady when isAvailable is false", async () => {
    isAvailableFn.mockReturnValue(false);
    vi.resetModules();
    const { callMiniAppReadyOnce } = await import("./telegram-ready");
    const { miniAppReady } = await import("@telegram-apps/sdk-react");
    const readyCall = miniAppReady as ReturnType<typeof vi.fn>;

    callMiniAppReadyOnce();
    expect(readyCall).not.toHaveBeenCalled();
  });
});
