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

// --- mocks ------------------------------------------------------------------

const mockJsonValue = vi.fn();

const mockHandle: Partial<JSHandle> = {
  jsonValue: mockJsonValue,
};

const mockPage = {
  waitForFunction: vi.fn(),
};

// ---------------------------------------------------------------------------

beforeEach(() => {
  vi.clearAllMocks();
  mockPage.waitForFunction.mockResolvedValue(mockHandle);
  mockJsonValue.mockResolvedValue(true);
});

import { pw_wait_predicate } from "./pw_wait_predicate";

// ---------------------------------------------------------------------------

describe("pw_wait_predicate", () => {
  it("defaults applied", async () => {
    const predicate = () => document.querySelector(".ready") !== null;

    await pw_wait_predicate(mockPage as never, predicate);

    expect(mockPage.waitForFunction).toHaveBeenCalledWith(
      predicate,
      undefined, // arg default
      { timeout: 5000, polling: 100 },
    );
  });

  it("arg passed through", async () => {
    const predicate = (sel: unknown) =>
      document.querySelectorAll(sel as string).length > 0;
    const arg = ".border-red";

    await pw_wait_predicate(mockPage as never, predicate, {
      timeoutMs: 2000,
      pollMs: 50,
      arg,
    });

    expect(mockPage.waitForFunction).toHaveBeenCalledWith(
      predicate,
      arg,
      { timeout: 2000, polling: 50 },
    );
  });

  it("jsonValue returned", async () => {
    const expected = { count: 3 };
    mockJsonValue.mockResolvedValue(expected);

    const result = await pw_wait_predicate(mockPage as never, "() => true");

    expect(result).toEqual(expected);
    expect(mockJsonValue).toHaveBeenCalledOnce();
  });

  it("message wraps timeout", async () => {
    const originalError = new Error("Timeout 5000ms exceeded");
    mockPage.waitForFunction.mockRejectedValue(originalError);

    await expect(
      pw_wait_predicate(mockPage as never, "() => false", {
        message: "no red-bordered card appeared",
      }),
    ).rejects.toThrow("no red-bordered card appeared: Timeout 5000ms exceeded");
  });

  it("error passthrough without message", async () => {
    const originalError = new Error("Something went wrong");
    mockPage.waitForFunction.mockRejectedValue(originalError);

    await expect(
      pw_wait_predicate(mockPage as never, "() => false"),
    ).rejects.toThrow("Something went wrong");
  });
});
