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

vi.mock("@/lib/rpa/env", () => ({
  isRpaAddressRushMode: vi.fn(() => false),
  isRpaBlindAddressFlow: vi.fn(() => false),
}));

vi.mock("@/workers/rpa/cargo-lock", () => ({
  dismissCargoPopoverOnly: vi.fn(async () => undefined),
}));

vi.mock("@/workers/rpa/page-prep", () => ({
  scrollQuoteWidgetIntoView: vi.fn(async () => undefined),
}));

vi.mock("@/lib/rpa/selector-specs", () => ({
  clickFirstVisibleFromSpecs: vi.fn(async () => false),
  getSelectorSpecs: vi.fn(() => []),
}));

function mockPage(innerText: string, buttonVisible = true): Page {
  const click = vi.fn(async () => undefined);
  const button = {
    isVisible: vi.fn(async () => buttonVisible),
    isDisabled: vi.fn(async () => false),
    scrollIntoViewIfNeeded: vi.fn(async () => undefined),
    click,
  };
  const roleButton = {
    first: vi.fn(() => button),
  };
  const widget = {
    innerText: vi.fn(async () => innerText),
    getByRole: vi.fn(() => roleButton),
    locator: vi.fn(() => ({
      filter: vi.fn(() => ({
        first: vi.fn(() => button),
      })),
      first: vi.fn(() => button),
    })),
  };
  return {
    locator: vi.fn(() => widget),
  } as unknown as Page;
}

describe("clickWidgetQuoteSubmitButton", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("表单未就绪时非 blind 模式不点击", async () => {
    const { clickWidgetQuoteSubmitButton } = await import(
      "@/workers/rpa/quote-capture/click-widget-quote-submit"
    );
    const page = mockPage("Freight details only");
    const clicked = await clickWidgetQuoteSubmitButton(page);
    expect(clicked).toBe(false);
  });

  it("blind 模式表单检测失败仍尝试点击", async () => {
    const env = await import("@/lib/rpa/env");
    vi.mocked(env.isRpaBlindAddressFlow).mockReturnValue(true);
    const { clickWidgetQuoteSubmitButton } = await import(
      "@/workers/rpa/quote-capture/click-widget-quote-submit"
    );
    const page = mockPage("Freight details only");
    const clicked = await clickWidgetQuoteSubmitButton(page);
    expect(clicked).toBe(true);
  });
});
