import { describe, expect, it, vi, afterEach } from "vitest";
import type { Page } from "playwright";
import { shouldKeepBrowserOpen } from "@/lib/rpa/env";
import {
  dismissCookieConsent,
  isQuoterWidgetHydrated,
} from "@/workers/rpa/page-prep";

describe("page-prep", () => {
  const envBackup = { ...process.env };

  afterEach(() => {
    process.env = { ...envBackup };
  });

  it("shouldKeepBrowserOpen：headed 默认保留", () => {
    process.env.RPA_HEADLESS = "false";
    delete process.env.RPA_KEEP_BROWSER_OPEN;
    expect(shouldKeepBrowserOpen()).toBe(true);
  });

  it("shouldKeepBrowserOpen：显式 false 关闭", () => {
    process.env.RPA_HEADLESS = "false";
    process.env.RPA_KEEP_BROWSER_OPEN = "false";
    expect(shouldKeepBrowserOpen()).toBe(false);
  });

  it("dismissCookieConsent：点击 Accept All", async () => {
    const click = vi.fn().mockResolvedValue(undefined);
    const page = {
      getByRole: vi.fn().mockReturnValue({
        first: () => ({
          isVisible: vi.fn().mockResolvedValue(true),
          click,
        }),
      }),
      locator: vi.fn().mockReturnValue({
        first: () => ({
          isVisible: vi.fn().mockResolvedValue(false),
          click,
        }),
      }),
      waitForTimeout: vi.fn().mockResolvedValue(undefined),
      evaluate: vi.fn().mockResolvedValue(undefined),
    } as unknown as Page;

    await dismissCookieConsent(page);
    expect(click).toHaveBeenCalled();
  });

  it("isQuoterWidgetHydrated：骨架屏文案无输入框时为 false", () => {
    expect(isQuoterWidgetHydrated(0, "Sign up and book now")).toBe(false);
  });

  it("isQuoterWidgetHydrated：有可编辑输入框时为 true", () => {
    expect(isQuoterWidgetHydrated(1, "Pick up from Search address")).toBe(true);
  });

  it("isQuoterWidgetHydrated：中文提货分区文案时 isQuoterWidgetHydrated 仍依赖输入框", () => {
    expect(isQuoterWidgetHydrated(0, "从何处取货 送货至")).toBe(false);
  });
});
