import { describe, expect, it, vi, beforeEach } from "vitest";
import type { Page } from "playwright";
import { AxelSelectionBridge } from "@/workers/rpa/axel-selection-bridge";

vi.mock("@/lib/rpa/env", () => ({
  getRpaPlaceFixMode: vi.fn().mockReturnValue("auto"),
}));

vi.mock("@/workers/rpa/fix-place/recon-helpers", () => ({
  loadReconVerdict: vi.fn().mockReturnValue({
    googleMapsLoaded: false,
    reactFiberKey: "not-found",
    placeChangedTriggerOk: false,
    verdict: "PLAN_B",
  }),
}));

vi.mock("@/workers/rpa/mothership-styled-suggestion-click", () => ({
  clickMothershipStyledSuggestion: vi.fn(),
  reopenStyledSuggestionDropdown: vi.fn(),
  waitForStyledSuggestionRows: vi.fn(),
}));

vi.mock("@/workers/rpa/fix-place/google-event-commit", () => ({
  commitViaGooglePlaceEvent: vi.fn(),
}));

vi.mock("@/workers/rpa/fix-place/react-state-commit", () => ({
  commitViaReactStateInjection: vi.fn(),
}));

vi.mock("@/workers/rpa/fix-place/browser-place-commit", () => ({
  commitViaBrowserPlaceFetch: vi.fn(),
}));

vi.mock("@/workers/rpa/fix-place/cdp-pac-commit", () => ({
  commitViaCdpDomClick: vi.fn(),
}));

vi.mock("@/workers/rpa/fix-place/direct-listener-commit", () => ({
  commitViaDirectPlaceChangedListener: vi.fn(),
}));

vi.mock("@/workers/rpa/fix-place/place-diagnostic-probe", () => ({
  isPlaceDiagEnabled: vi.fn().mockReturnValue(false),
  setPlaceDiagMark: vi.fn(),
  logPlaceDiagnostic: vi.fn(),
  writePlaceDiagnosticArtifact: vi.fn(),
}));

import { commitPlaceWithStrategy } from "@/workers/rpa/fix-place/place-commit-strategy";
import { clickMothershipStyledSuggestion } from "@/workers/rpa/mothership-styled-suggestion-click";
import { commitViaBrowserPlaceFetch } from "@/workers/rpa/fix-place/browser-place-commit";
import { commitViaCdpDomClick } from "@/workers/rpa/fix-place/cdp-pac-commit";
import { commitViaDirectPlaceChangedListener } from "@/workers/rpa/fix-place/direct-listener-commit";
import { commitViaGooglePlaceEvent } from "@/workers/rpa/fix-place/google-event-commit";
import { commitViaReactStateInjection } from "@/workers/rpa/fix-place/react-state-commit";

describe("place-commit-strategy", () => {
  const page = {} as Page;
  let bridge: AxelSelectionBridge;

  beforeEach(() => {
    vi.clearAllMocks();
    bridge = new AxelSelectionBridge();
    bridge.recordPlaceCommit("ChIJ_test");
    vi.spyOn(bridge, "waitForPlaceCommit").mockResolvedValue(true);
    vi.spyOn(bridge, "hasSuccessfulPlaceNetworkRequest").mockReturnValue(true);
  });

  it("PLAN_B 时跳过 google-event 与 react-state", async () => {
    vi.mocked(clickMothershipStyledSuggestion).mockResolvedValue({
      clicked: false,
      reason: "miss",
    });
    vi.mocked(commitViaCdpDomClick).mockResolvedValue({
      ok: false,
      method: "cdp-dom-click-failed",
    });
    vi.mocked(commitViaDirectPlaceChangedListener).mockResolvedValue({
      ok: false,
      method: "direct-listener-invoke-failed",
    });
    vi.mocked(commitViaBrowserPlaceFetch).mockResolvedValue({
      ok: false,
      method: "browser-place-fetch",
    });

    const result = await commitPlaceWithStrategy(
      page,
      bridge,
      "ChIJ_test",
      "123 Test St, Los Angeles, CA, USA",
      "pickup",
      undefined,
      {
        input: {} as never,
        query: {
          street: "123 Test St",
          city: "Los Angeles",
          state: "CA",
          zip: "",
        },
      },
    );

    expect(result.ok).toBe(false);
    expect(commitViaGooglePlaceEvent).not.toHaveBeenCalled();
    expect(commitViaReactStateInjection).not.toHaveBeenCalled();
  });

  it("styled-click 成功且 place 200 时直接返回", async () => {
    vi.mocked(clickMothershipStyledSuggestion).mockResolvedValue({
      clicked: true,
      method: "gold-exact-text",
      matchedText: "123 Test St",
    });

    const result = await commitPlaceWithStrategy(
      page,
      bridge,
      "ChIJ_test",
      "123 Test St, Los Angeles, CA, USA",
      "pickup",
      undefined,
      {
        input: {} as never,
        query: {
          street: "123 Test St",
          city: "Los Angeles",
          state: "CA",
          zip: "",
        },
      },
    );

    expect(result).toEqual({ ok: true, method: "gold-exact-text" });
  });

  it("cdp-click 成功且 place 200 时返回 cdp 方法", async () => {
    vi.mocked(clickMothershipStyledSuggestion).mockResolvedValue({
      clicked: false,
      reason: "miss",
    });
    vi.mocked(commitViaCdpDomClick).mockResolvedValue({
      ok: true,
      method: "cdp-pac-item-0",
    });
    vi.mocked(commitViaDirectPlaceChangedListener).mockResolvedValue({
      ok: false,
      method: "direct-listener-no-network",
    });
    vi.mocked(commitViaBrowserPlaceFetch).mockResolvedValue({
      ok: false,
      method: "browser-place-fetch",
    });

    const result = await commitPlaceWithStrategy(
      page,
      bridge,
      "ChIJ_test",
      "123 Test St, Los Angeles, CA, USA",
      "pickup",
      undefined,
      {
        input: {} as never,
        query: {
          street: "123 Test St",
          city: "Los Angeles",
          state: "CA",
          zip: "",
        },
      },
    );

    expect(result).toEqual({ ok: true, method: "cdp-pac-item-0" });
    expect(commitViaDirectPlaceChangedListener).not.toHaveBeenCalled();
  });
});
