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

const mocks = vi.hoisted(() => ({
  waitForVerificationClear: vi.fn(),
  stepPause: vi.fn(async () => {}),
  randomPause: vi.fn(async () => {}),
  humanClick: vi.fn(async () => {}),
  waitForManualVerificationIfNeeded: vi.fn(async () => false),
}));

vi.mock("./human.js", () => ({
  humanClick: mocks.humanClick,
  randomPause: mocks.randomPause,
  stepPause: mocks.stepPause,
  waitForManualVerificationIfNeeded: mocks.waitForManualVerificationIfNeeded,
  waitForVerificationClear: mocks.waitForVerificationClear,
}));

import { pickPreferredDetailTitle, scanOfferContactsByNavigation } from "./contact-page-navigation.js";

class FakeFrame {
  constructor(private readonly page: FakePage) {}

  url() {
    return this.page.url();
  }

  async evaluate() {
    return this.page.bodyText;
  }
}

class FakeLocator {
  first() {
    return this;
  }

  filter() {
    return this;
  }

  async count() {
    return 0;
  }

  async isVisible() {
    return false;
  }
}

class FakePage {
  bodyText = "";
  currentUrl = "about:blank";
  gotoCalls: string[] = [];
  screenshotCalls: string[] = [];
  closed = false;

  constructor(private readonly mode: "captcha" | "detail") {
    if (mode === "captcha") {
      this.currentUrl = "https://detail.1688.com/punish";
      this.bodyText = "验证码拦截 亲，请拖动下方滑块完成验证 通过验证以确保正常访问";
    } else {
      this.currentUrl = "https://detail.1688.com/offer/1.html";
      this.bodyText = "岩棉板 TR10 容重100kg 商品详情 价格 起批 主图";
    }
  }

  isClosed() {
    return this.closed;
  }

  frames() {
    return [new FakeFrame(this)];
  }

  url() {
    return this.currentUrl;
  }

  async goto(url: string) {
    this.gotoCalls.push(url);
    if (this.mode === "detail") {
      this.currentUrl = url;
    }
    return { ok: () => true, status: () => 200 };
  }

  async waitForLoadState() {}

  async waitForFunction() {
    if (this.mode === "detail") {
      return true;
    }
    throw new Error("not ready");
  }

  async evaluate(_fn: unknown, arg?: unknown) {
    if (Array.isArray(arg)) {
      return this.mode === "detail" ? ["岩棉板 TR10 容重100kg"] : [];
    }
    return this.bodyText;
  }

  async screenshot(options: { path: string }) {
    this.screenshotCalls.push(options.path);
  }

  locator() {
    return new FakeLocator();
  }

  async waitForURL() {}

  async close() {
    this.closed = true;
  }
}

class FakeContext {
  page: FakePage;

  constructor(mode: "captcha" | "detail") {
    this.page = new FakePage(mode);
  }

  async newPage() {
    return this.page;
  }
}

beforeEach(() => {
  mocks.waitForVerificationClear.mockReset();
  mocks.stepPause.mockClear();
  mocks.randomPause.mockClear();
  mocks.humanClick.mockClear();
  mocks.waitForManualVerificationIfNeeded.mockClear();
});

describe("pickPreferredDetailTitle", () => {
  it("prefers the detail page title when the search card title is interaction prompt copy", () => {
    expect(
      pickPreferredDetailTitle(
        "点击可以直接和卖家交流选好的宝贝，或者互动购网站体验，还支持语音视频哦。",
        "国标BV1.5 2.5 4 6平方单芯铜芯电线阻燃防水电源线电缆线批发",
        "鸿海线缆有限公司",
      ),
    ).toBe("国标BV1.5 2.5 4 6平方单芯铜芯电线阻燃防水电源线电缆线批发");
  });

  it("keeps the current title when the detail title is empty or lower quality", () => {
    expect(
      pickPreferredDetailTitle(
        "BVR 2.5平方单芯软铜线蓝 珠江工",
        "",
        "鸿海线缆有限公司",
      ),
    ).toBe("BVR 2.5平方单芯软铜线蓝 珠江工");
  });

  it("rejects generated resource identifiers from detail title diagnostics", () => {
    expect(
      pickPreferredDetailTitle(
        "1kV冷缩电缆终端头 120mm2 铝芯",
        "hO7TX2rRhkJDVqeFGucSXQ|aetU-Q|BUpWdg_0|By-uiQ|0",
        "",
      ),
    ).toBe("1kV冷缩电缆终端头 120mm2 铝芯");
  });
});

describe("scanOfferContactsByNavigation screenshots", () => {
  it("does not screenshot or continue to contact page when offer captcha remains unresolved", async () => {
    mocks.waitForVerificationClear.mockResolvedValue(false);
    const context = new FakeContext("captcha");

    const result = await scanOfferContactsByNavigation(context as never, {
      offerUrl: "https://detail.1688.com/offer/1.html",
      merchantUrl: "https://shop1.1688.com",
      timeoutMs: 1000,
      screenshotPath: "/tmp/offer-1.jpg",
      merchantName: "测试商家",
      currentTitle: "岩棉板 TR10 容重100kg",
    });

    expect(result).toMatchObject({
      status: "error",
      reason: "offer_detail_captcha_unresolved",
      screenshotPath: "",
      offerScreenshotStatus: "captcha_unresolved",
      contactFetchStatus: "skipped",
    });
    expect(context.page.screenshotCalls).toEqual([]);
    expect(context.page.gotoCalls).toEqual(["https://detail.1688.com/offer/1.html"]);
  });

  it("screenshots only after captcha is clear and offer detail content is ready", async () => {
    mocks.waitForVerificationClear.mockResolvedValue(true);
    const context = new FakeContext("detail");

    const result = await scanOfferContactsByNavigation(context as never, {
      offerUrl: "https://detail.1688.com/offer/1.html",
      merchantUrl: "",
      timeoutMs: 1000,
      screenshotPath: "/tmp/offer-1.jpg",
      merchantName: "测试商家",
      currentTitle: "岩棉板 TR10 容重100kg",
    });

    expect(result.offerScreenshotStatus).toBe("ok");
    expect(result.screenshotPath).toBe("/tmp/offer-1.jpg");
    expect(context.page.screenshotCalls).toEqual(["/tmp/offer-1.jpg"]);
  });
});
