import { describe, expect, it, vi } from "vitest";
import {
  isFlockLoggedInQuoteForm,
  selectFlockComboboxOption,
} from "@/workers/rpa/flock/logged-in-form";

function mockLocator(opts: {
  count?: number;
  visible?: boolean;
  click?: () => Promise<void>;
}) {
  const click = opts.click ?? (async () => undefined);
  return {
    first: () => mockLocator(opts),
    count: async () => opts.count ?? 0,
    isVisible: async () => opts.visible ?? false,
    click,
    waitFor: async () => undefined,
    fill: async () => undefined,
    getAttribute: async () => null,
    scrollIntoViewIfNeeded: async () => undefined,
    page: () => ({ isClosed: () => false }),
  };
}

describe("flock logged-in form", () => {
  it("识别 Let's build a quote 为登录后表单", async () => {
    const heading = mockLocator({ count: 1, visible: true });
    const page = {
      getByTestId: () => mockLocator({ count: 0 }),
      getByRole: (role: string) => {
        if (role === "heading") return heading;
        return mockLocator({ count: 0 });
      },
      getByText: () => mockLocator({ count: 0 }),
    };
    expect(await isFlockLoggedInQuoteForm(page as never)).toBe(true);
  });

  it("combobox 按候选选 option", async () => {
    const clicks: string[] = [];
    const option70 = mockLocator({
      count: 1,
      visible: true,
      click: async () => {
        clicks.push("70");
      },
    });
    const combo = mockLocator({
      count: 1,
      visible: true,
      click: async () => {
        clicks.push("open");
      },
    });
    const page = {
      getByRole: (role: string, opts?: { name?: RegExp | string }) => {
        if (role === "combobox") return combo;
        if (role === "button") return mockLocator({ count: 0 });
        if (role === "option") {
          const name = String(opts?.name ?? "");
          if (name.includes("70") || name === "70") return option70;
          return mockLocator({ count: 0 });
        }
        return mockLocator({ count: 0 });
      },
      waitForTimeout: async () => undefined,
      keyboard: { press: async () => undefined },
    };

    const ok = await selectFlockComboboxOption(
      page as never,
      /Freight Class/i,
      ["70", "50"],
    );
    expect(ok).toBe(true);
    expect(clicks).toContain("open");
    expect(clicks).toContain("70");
  });
});
